Home > Software design >  Get a specific object from an array of objects
Get a specific object from an array of objects

Time:07-29

Here is the sample input

const arr = [{name:'bruce', surname: 'wayne'}, {name:'clark', surname:'kent'}]

How to get an output that would be like

result = {bruce:'wayne', clark:'kent'}

Thank you in advance

CodePudding user response:

You could use .reduce() like so:

const arr = [
  {name: "bruce", surname: "wayne"},
  {name: "clark", surname: "kent"}
];

const result = arr.reduce(
  (acc, curr) => ({...acc, [curr.name]: curr.surname}),
  {}
);

console.log(result);

CodePudding user response:

Create a new object with key that equals to name and value that equals to surname.

const arr = [{name:'bruce', surname: 'wayne'}, {name:'clark', surname:'kent'}]

const completeNameArrObj =  arr.map(item => ({[item.name]:item.surname}));

console.info(completeNameArrObj);

  • Related