I'm looping through an array of objects, each of which has a nested array of objects:
_each(this.props.chartProps.data, function(item){
//item.values is an array of objects
});
I want to add the same key value pair to all of the objects within the nested array. In other words, all of the objects in item.values should have a new key value pair added, call it newpair
.
I'd like to clone it.
Is there a quick lodashian way to do this?
I'm looping through an array of objects, each of which has a nested array of objects:
_each(this.props.chartProps.data, function(item){
//item.values is an array of objects
});
I want to add the same key value pair to all of the objects within the nested array. In other words, all of the objects in item.values should have a new key value pair added, call it newpair
.
I'd like to clone it.
Is there a quick lodashian way to do this?
Share Improve this question edited Aug 10, 2016 at 13:55 Union find asked Aug 10, 2016 at 13:47 Union findUnion find 8,18017 gold badges69 silver badges117 bronze badges 8- if you use react it's not a good idea to mutate your props – Maxx Commented Aug 10, 2016 at 13:50
-
2
In vanilla:
item.values = item.values.map(value => { value.foo = bar; return value; })
? – gcampbell Commented Aug 10, 2016 at 13:50 - @gcampbell Why you're cloning the array? – Andreas Commented Aug 10, 2016 at 13:52
-
2
Then just use
forEach
instead?item.values.forEach( o => o[key] = "value");
– adeneo Commented Aug 10, 2016 at 13:53 - 4 I wonder why lodash is still used for this stuff. – trincot Commented Aug 10, 2016 at 13:56
2 Answers
Reset to default 4I used a straightforward map array prototype method:
item.values = item.values.map(value => { value.foo = bar; return value; });
Something like this ?
function modify(o) { /* set prop here */}
var objects = _.flatMap(array, function(o) { return o.values; });
_.forEach(objects, modify);