简体   繁体   English

Lodash map 值来自对象数组中的嵌套 object

[英]Lodash map value from nested object in array of objects

I am trying to use a lodash's map function to extract a value from a nested object in an array of objects and store it in a new key.我正在尝试使用 lodash 的 map function 从对象数组中的嵌套 object 中提取值并将其存储在新键中。 But always got stuck with lodash and am getting an error.但总是被 lodash 卡住并且出现错误。 Any help would be much appreciated.任何帮助将非常感激。 The key nested will always be an array of 1 object. nested的键将始终是 1 个 object 的数组。

const _ = require('lodash');

var all_data = [{id: 'A', nested: [{id: '123'}]}, {id: 'B', nested: [{id: '456'}]}];

_.map(all_data, (data) => ({
  data.nested_id = data.nested[0].id;

}));
console.log(all_data)

Desired output: [{id: 'A', nested_id: '123', nested: [{id: '123'}]}, {id: 'B', nested_id: '456', nested: [{id: '456'}]}]所需的 output: [{id: 'A', nested_id: '123', nested: [{id: '123'}]}, {id: 'B', nested_id: '456', nested: [{id: '456'}]}]

You don't have to use lodash for this simple transformation.对于这个简单的转换,您不必使用 lodash。

const allData = [{id: 'A', nested: [{id: '123'}]}, {id: 'B', nested: [{id: '456'}]}]

const transformedData = allData.map(item => ({
  ...item,
  nested_id: item.nested[0].id
}))

But here's the lodash version if you really want to use it.但是,如果您真的想使用它,这里是 lodash 版本。

const transformedData = _.map(allData, (item) => ({
  ...item,
  nested_id: item.nested[0].id,
}))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM