最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to add key value pair to all objects in an array with lodash - Stack Overflow

programmeradmin6浏览0评论

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
 |  Show 3 more ments

2 Answers 2

Reset to default 4

I 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);
发布评论

评论列表(0)

  1. 暂无评论