const arr = [{name:"abc", age:10},{name:"xyz", age:20},{name:"asd", age:12}];
Need output as:
{abc: {age:10}, xyz: {age:20}, asd: {age: 12}}
You could use reduce
to iterate through all the array items and build a new object with the desired format:
const arr = [{name:"abc", age:10},{name:"xyz", age:20},{name:"asd", age:12}];
const result = arr.reduce((acc, currentValue) => {
// grab the name in a separate variable and keep the rest of the object in another using object destructuring
const { name, ...rest } = currentValue;
// use the name as a key in the result and assign the rest as the value
acc[name] = rest;
return acc;
}, {});
console.log(result)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments