0

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

2
  • Is there a reason why you are using lodash? The immediate problem is that you should return data from the callback of _.map but this can be done in pure JS and without mutation: all_data.map((obj) => ({ ...obj, nested_id: obj.nested[0].id })) Commented Feb 3, 2021 at 1:04
  • I think you are better off using Vanilla JS. Commented Feb 3, 2021 at 1:04

1 Answer 1

1

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, })) 
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. This works great. As a slight variant if I wanted to removed the property nested is it possible to do with the way that spread operator is used?
@user2242044 If you know the object only has the 3 properties shared in the code snippet, you can do allData.map(item => ({ id: item.id, nested_id: item.nested[0].id }))
thanks. This was just a simple example. What if it has a lot more fields than just 3 and I don't want to write them all out?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.