简体   繁体   中英

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. But always got stuck with lodash and am getting an error. Any help would be much appreciated. The key nested will always be an array of 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'}]}]

You don't have to use lodash for this simple transformation.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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