Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

146
Views
How do I create an object from array of objects using javascript?
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}}
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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)

about 4 years ago · Juan Pablo Isaza Report

0

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)

about 4 years ago · Juan Pablo Isaza Report

0

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));

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!