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)
This answer only works if all objects have unique names. If there are any duplicates, some of the values WILL be overwritten.
const arr = [{name:"abc", age:10},{name:"xyz", age:20},{name:"asd", age:12}];
const newObject = {};
arr.forEach(item => {
const name = item.name;
delete item.name;
newObject[name] = item;
})
console.log(arr)
console.log(newObject)
Is this enough for what you want to do?
const arr = [
{ name: "abc", age: 10 },
{ name: "xyz", age: 20 },
{ name: "asd", age: 12 },
];
function transform(data) {
let newObject = {};
for (let element of data) {
newObject = { ...newObject, [element.name]: { age: element.age } };
}
return newObject;
}
console.log(transform(arr));