I have an object array as follows:
products = [
{
id: 1,
title: "Product 1",
specifications: {
price: 1.55,
discount: 15,
attributes: [
{
l1: 100,
l2: 80
height:200,
weight: 15,
parameters: [
{
id: 199199 // this is how I identify the parameter
size: 185 // this is what I want to change
}, ...
]
}, ...
]
}
}, ...
]
... and an array of changes to parameters I want to apply, for example: change size to 189 where product.specifications.attributes.parameters.id == 199199.
I'd like to do this without flattening any elements as they are part of a Vue.js data structure, it will break the reactivity.
How could I do this? I am open to using Underscore or lo-dash
This looks ugly, but it is effective:
To make it more dynamic, let's use variables: identifier will be your '199199' value and new_size for the '189' value.
methods: {
updateRecord: function(identifier, new_size) {
this.products.map(function(product) {
product.specifications.attributes.map(function(attribute) {
attribute.parameters.map(function(parameter) {
if (parameter.id == identifier) parameter.size = new_size;
})
});
});
}
}
Here is a working fiddle: https://jsfiddle.net/crabbly/eL7et9e8/
_.forEach(products, function(product) {
_.forEach(_.get(product, 'specifications.attributes', []), function(attribute) {
_.set(_.find(attribute.parameters, {id: 199199}), 'size', 189);
});
});
I believe what you want is underscore's findIndex() - http://underscorejs.org/#findIndex. Once you find which element in the array you want to apply the changes to (comparing the nested id to what you are looking for) you can then make the change to that particular element.
Related
I have a javascript object with nested objects like this:
Object {
Id: 1,
Descendants: [{
Object {
id:2
Descendants:[
{Object
{id:3
Descendants[]
}}]}]
Now I want to iterate through all of the descendant properties and print them.
What would be the cleanest way to do this?
Thanks a lot in advance!
You could try this:
const o = {
id: 1,
Descendants: [
{
id: 2,
Descendants: [
{
id: 3,
Descendants: [],
},
],
},
],
}
function doSomething(o) {
// Write Do whatever you want to do with the objects
console.log(o.id)
// And to the recursively
for (const child of o.Descendants) {
doSomething(child)
}
}
doSomething(o)
Here is the code (it fails to compile at the sentence that builds the state2, i.e. at the second spread):
let line_id = 6;
let state = {
invoice: {
id: 1015,
description: 'web order',
},
lines: [
{id: 5, description: 'phone', color: 'black'},
{id: 6, description: 'tablet', color: 'blue'},
{id: 7, description: 'computer', color: 'gray'},
]
};
//this alert and this access pattern works, so, I would like to use
//.find... to access element in spread... structure as well
//alert(state['lines'].find(line=>line['id']==line_id)['description']);
let state2 = {
...state,
['lines']: { ...state['lines'],
find(line=>line['id']==line_id): { ...state['lines'].find(line=>line['id']==line_id),
['description']: 'TV',
},
},
};
alert(state2['lines'].find(line=>line['id']==line_id)['description']);
I have state structure, I access lines array, I access the specific line by name-value pair id=6 and I would like to change the value of the field description. This effort is the continuation of https://stackoverflow.com/a/64116308/1375882 in which I am trying to create the general procedure, that use the spread... syntax and the access-by-name strategy for updating the complex object/array tree. In fact - this complex tree is the state of the Redux reducer and that update happend in the action that process the valueSetter function of the AgGrid. But - this is generally the interesting exercise by itself to better understand spread... and JavaScript and JSON structure in JavaScript.
So - the only question is: how to write line
find(line=>line['id']==line_id): { ...state['lines'].find(line=>line['id']==line_id),
so that the code compiles? How can I access the certain element of the array by name-value pair in this setting:
Note, that I am trying to build general code:
find(line=>line[keyFieldName]==keyFieldValue): { ...state['lines'].find(line=>line[keyFieldName]==keyFieldValue),
that uses arbitrary field names and field values - so that such handler can update the any field of the any record of arbitrary 2D AgGrid in React/Redux setting.
The desired result of my code: 1) it should compile; 2) the second alert should return 'TV'.
If I understood correctly what you want to achieve, this should work:
let line_id = 6;
let state = {
invoice: {
id: 1015,
description: 'web order',
},
lines: [{
id: 5,
description: 'phone',
color: 'black'
},
{
id: 6,
description: 'tablet',
color: 'blue'
},
{
id: 7,
description: 'computer',
color: 'gray'
},
]
};
const stateKeyId = 'lines';
const itemKeyId = 'id';
const itemAttr = 'description'
let state2 = {
...state,
[stateKeyId]: state[stateKeyId].map(item => {
if (item[itemKeyId] == line_id) {
return ({
...item,
[itemAttr]: 'TV'
});
}
return item
})
}
console.log(state2);
find(line=>line['id']==line_id) should become [find(line=>line['id']==line_id)], since just like the string it must be between square brackets for js to work properly.
Also, if you are using find from lodash, it will return the object, therefore if you need to use the id as key you can do something like:
[get(find(line => line['id'] === line_id]), 'id')]: whatever
a few observations though:
always please always use === over == in js
avoid snake_case, use camelCase with js, since it's standard
your code is not actually handling missing items correclty, if you need to do so split it in multiple lines since it would be more comprehensible
You can use the map method from arrays to return different elements based on the original one.
Here's how you could use it:
line_id = 6;
state = {
invoice: {
id: 1015,
description: 'web order',
},
lines: [
{id: 5, description: 'phone', color: 'black'},
{id: 6, description: 'tablet', color: 'blue'},
{id: 7, description: 'computer', color: 'gray'},
]
};
state2 = {
...state,
lines: state.lines.map(line => {
if (line.id === line_id)
return { ...line, description: 'YT' }
return { ...line }
})
};
alert(state2['lines'].find(line=>line['id']==line_id)['description']);
I'm looking for the most concise way to convert an array to an object while plucking the field used as the key for each result.
This is the solution I found, and I'm wondering if there's an easier way.
r.table('product').fold({}, function(products, product) {
return products.merge(
r.object(
product('id').coerceTo('string'),
product.without('id')
)
);
})
Thanks!
Example
// Input:
[{ id: 0, price: 19.99 }, { id: 1, price: 24.99 }]
// Output:
{ "0": { price: 19.99 }, "1": { price: 24.99 } }
I'm not an expert, but AFAIK, using fold() directly on a table will "stop subsequent commands from being parallelized":
https://www.rethinkdb.com/docs/optimization/
So, if I'm not mistaken, if the order is not important it might be better to choose reduce() over fold(), e.g.
table.map(function(row) {
return r.object(
row('id').coerceTo('string'), row.without('id')
)
})
.reduce(function(left, right) {
return left.merge(right)
})
So for example I have a MAIN array with all the information I need:
$scope.songs = [
{ title: 'Reggae', url:"#/app/mworkouts", id: 1 },
{ title: 'Chill', url:"#/app/browse", id: 2 },
{ title: 'Dubstep', url:"#/app/search", id: 3 },
{ title: 'Indie', url:"#/app/search", id: 4 },
{ title: 'Rap', url:"#/app/mworkouts", id: 5 },
{ title: 'Cowbell', url:"#/app/mworkouts", id: 6 }
];
I want to put only certain objects into another array without typing in each of the objects so the end result will look like
$scope.array1 = [
{ title: 'Reggae', url:"#/app/mworkouts",id: 1 },
{ title: 'Cowbell', url:"#/app/mworkouts",id: 6 }
];
I have tried this with no luck:
$scope.array1 = [
{ $scope.songs[1] },
{ $scope.songs[6] }
];
I will have to do a bunch of these so typing in each object would take forever, is there any faster way to do this? Thanks in advance :)
You need to do something like this:
$scope.array1 = $scope.songs.filter(function (song) {
return (song.title == "Reggae" || song.title == "Cowbell");
});
Here, the filter function will give you a filtered new array to be replaced for the original scope value.
Or in simple way, using the array indices, you can use:
$scope.array1 = [ $scope.songs[0] , $scope.songs[5] ];
You need to remove the braces since it's already an object. Although the array index starts from 0 so change index value based on 0.
$scope.array1 = [
$scope.songs[0] ,
$scope.songs[5]
];
I have 2 separate json objects coming from the server. Json A below is of a Car model object which is fetch when looking at a car. Json B is meta data which is used throughout the whole application when the web page first loads.
What I need to do is have a lookup on wheel_id while doing a ng-repeat on wheel_handlers so it returns the wheel object from json B and then I can use this within the view and print the results. I think I need to do something with the ng-repeat but I'm not sure to be honest.
A - Car model
[{
id: 14,
name: "Audi",
wheel_handlers: [
{
id: 9,
wheel_id: 62,
arguments: {
amount: 10
}
}
]
}]
B - wheel
{
id: 62,
name: "Change Wheel Size",
arguments: [
{
id: 25,
description: "amount"
}
]
}
I am assuming the following: The Json "A" may include several cars, but also several wheel_handlers (because there is an array at wheel_handler). So the JSON for the cars may also look like this:
[
{
id: 14,
name: "Audi",
wheel_handlers: [
{
id: 9,
wheel_id: 62,
arguments: {
amount: 10
}
},
{
id: 12,
wheel_id: 65,
arguments: {
amount: 12
}
},
{
id: 15,
wheel_id: 30,
arguments: {
amount: 8
}
}
]
},
{
id: 16,
name: "Mercedes",
wheel_handlers: [
{
id: 9,
wheel_id: 62,
arguments: {
amount: 10
}
},
{
id: 12,
wheel_id: 65,
arguments: {
amount: 12
}
}
]
}
]
For the JSON file B I assume that you also meant an Array, which could contain several wheel definitions. As an example:
[
{
id: 62,
name: "Change Wheel Size",
arguments: [
{
id: 25,
description: "amount"
}
]
},
{
id: 65,
name: "test wheel",
arguments: [
{
id: 25,
description: "amount"
}
]
},
{
id: 30,
name: "another wheel",
arguments: [
{
id: 25,
description: "amount"
}
]
}
]
If this is the case, you could iterate over the cars and while iterating call a helper function in the AngularJS controller. You call this helper function and give wheel_handlers of the current car as a parameter. This helper function then checks the wheel_id of each wheel_handler entry and searches these ids in the JSON b file - the wheel definitions. The helper function returns an array containing the wheels, so in the view you may iterate over the wheels. This will use a nested ng-repeat, because at first you iterate over the cars and while iterating over the cars you will iterate over the wheels.
Here is an example of the controller part. I used $scope.cars as the JSON A, and $scope.wheels as JSON B.
var testApp = angular.module('testApp', []);
testApp.controller('testContr', function ($scope) {
$scope.cars = [];
$scope.wheels = [];
$scope.getWheelsByIds = function (wheel_handlers) {
var wheelIds = [];
var returnArray = [];
for (var wheelKey in wheel_handlers) {
wheelIds.push(wheel_handlers[wheelKey].wheel_id);
}
for (var key in $scope.wheels) {
console.log(wheelIds.indexOf($scope.wheels[key].id));
if (wheelIds.indexOf($scope.wheels[key].id) > -1) {
returnArray.push($scope.wheels[key]);
}
}
return returnArray;
}
});
The necessary HTML part could look like this:
<div ng-app="testApp" ng-controller="testContr">
<div ng-repeat="car in cars" ng-init="wheels = getWheelsByIds(car.wheel_handlers)">
<span>Car name: {{car.name}}</span><br/>
<div ng-repeat="wheel in wheels">
<span>Wheel name: {{wheel.name}}</span><br/>
</div>
<br/>
<br/>
</div>
</div>
I create a fiddle demonstration with the test data, view it here: http://jsfiddle.net/4F3YD/10/
You can nest ng-repeats like that, although I'm not sure what you want to achieve
following code will repeat through cars, then wheels in cars and display wheels from object B(wheels) that match the car wheel id, hope that makes sense
<div ng-repeat="car in CarModels">
<div ng-repeat="wheel in car.wheel_handlers">
{{Wheels | filter:wheel.wheel_id}}
</div>
</div>
You can make use of angular filter over here. In the filter function you can check for the id in the second json.
More Documentation on Angular Filter
Code Example:
<div ng-repeat="element in wheel | filterIds:element.id">
And filter Function:
.filter('filterIds', function () {
return function(id) {
$scope.carModel.forEach(function(car){
if(id == car.id)
return id;
});
}
})