2

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?

8
  • if you use react it's not a good idea to mutate your props Commented Aug 10, 2016 at 13:50
  • 2
    In vanilla: item.values = item.values.map(value => { value.foo = bar; return value; }) ? Commented Aug 10, 2016 at 13:50
  • @gcampbell Why you're cloning the array? Commented Aug 10, 2016 at 13:52
  • 2
    Then just use forEach instead? item.values.forEach( o => o[key] = "value"); Commented Aug 10, 2016 at 13:53
  • 4
    I wonder why lodash is still used for this stuff. Commented Aug 10, 2016 at 13:56

2 Answers 2

4

I used a straightforward map array prototype method:

item.values = item.values.map(value => { value.foo = bar; return value; });
Sign up to request clarification or add additional context in comments.

2 Comments

In this way you are mutating the array, not clear if it's what OP wanted
Probably you can do value => ({foo: bar, ...value})
1

Something like this ?

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

var objects = _.flatMap(array, function(o) { return o.values; });
_.forEach(objects, modify);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.