如何迭代嵌套的对象数组并更新它们的属性

3

我有以下格式的数据

objects = [{
  ...someProperties,
  itemsOfInterest: [
    {
      ...someProperties,
    },
    {
      ...someProperties,
    },
    ...
  ],
},
{<same stuff>},
]

我想遍历每个itemsOfInterest中的每个项目,并对每个项目执行一些逻辑以添加一个字段。我希望这个更改能够反映在原始对象上(或者至少得到一个原始形状的对象)。

我尝试过类似以下的代码:

_.map(objects, (object) => {
        const itemsOfInterest = _.map(object.itemsOfInterest, (itemOfInterest) => {
            itemOfInterest.newProperty = true;
            return itemOfInterest;
        });
        object.itemsOfInterest = itemsOfInterest;
    });

但那显然是错误的。我对JS很新,所以任何帮助都会受到赞赏!lodash 的使用也很好。

3个回答

3
objects.forEach(object=>{
  object.itemsOfInterest.forEach(item=>{
    if(true) item.newProp = 3; // put your own logic here
  })
})

1
你应该在代码中为 OP 包含一些解释... - dale landry
不错,这个解决了问题。我一直在努力让 forEach 正确运行。 - PeachWaffle

2
您可以使用_.map()方法遍历对象数组和itemsOfInterest数组。然后根据需要更新对象。
const modifiedObjects = _.map(objects, (object) => {
  const itemsOfInterest = _.map(object.itemsOfInterest, (itemOfInterest) => {
    return _.assign({}, itemOfInterest, { newProperty: true });
  });
  return _.assign({}, object, { itemsOfInterest });
});

0

我最终使用的是:

_.forEach(objects, (object) =>
    _.forEach(object.itemsOfInterest, (itemOfInterest) => {
        <setting logic here>
    })
)

比我之前尝试的要容易得多!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接