Skip to content
Advertisement

How to add key value pair to all objects in an array with lodash

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?

Advertisement

Answer

Something like this ?

function modify(o) { /* set prop here */}

var objects = _.flatMap(array, function(o) { return o.values; });
_.forEach(objects, modify);
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement