1

Can someone help me generate a new array of objects from an existing one using lodash? I've been trying a combination of _.zipObject and map but to no avail... basically, I have an array of objects like:

const names = [
  {
    first_name: 'nedd',
    given_name: 'cersei'
  },
  {
    first_name: 'tyrion',
    given_name: 'tywin'
  }
]

However, I want it to look like:

[
  {
    name: 'nedd'
  },
  {
    name: 'cersei'
  },
  {
    name: 'tyrion'
  },
  {
    name: 'tywin'
  },
]

I have tried various iterations of:

const newArray = _.zipObject( names, _.fill( Array(names.length), {name: ['first_name' || 'given_name']} ) );

But without any luck... can someone help?

Thanks in advance!

2 Answers 2

2

This might work:

_.flatMap(names, (n)=> [{name: n.first_name}, {name: n.given_name}]);
Sign up to request clarification or add additional context in comments.

Comments

2

Use _.flatMap combined with _.map:

_.flatMap(names, (nameObj) => _.map(nameObj, (objVal) => { return { name: objVal }; }));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.