user2242044
user2242044

Reputation: 9213

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'}]}]

Upvotes: 0

Views: 2804

Answers (1)

Arun Kumar Mohan
Arun Kumar Mohan

Reputation: 11905

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,
}))

Upvotes: 1

Related Questions