• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

87
Views
Convert array of objects into a single object

I have the following array for example -

[
  {
    name: "abc",
    value: "1"
  },
  {
    name: "xyz",
    value: "2"
  },
  {
    name: "abc",
    value: "3"
  },
  {
    name: "abc",
    value: "4"
  },
  {
    name: "xyz",
    value: "5"
  },
]

Now, I want to reduce this array into a single object by grouping value with the same name together into an array. Something like this -

{
  abc: [1, 3, 4],
  xyz: [2, 5]
}

How do I do this using reduce in JavaScript?

I'm not sure if this the right approach but I have tried something like this and it doesn't give me the desired output.

const data = arr.reduce((acc, item) => {
  return {
    ...acc,
    [item.name]: [item.value, acc[item.value]]
  };
});
about 3 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You were on the right track with your answer, but you need to check if acc already has a key of item.name:

const data = [{
    name: "abc",
    value: "1"
  },
  {
    name: "xyz",
    value: "2"
  },
  {
    name: "abc",
    value: "3"
  },
  {
    name: "abc",
    value: "4"
  },
  {
    name: "xyz",
    value: "5"
  },
]

const result = data.reduce((acc, { name, value }) => ({
  ...acc,
  [name] : [...(acc[name] || []), value]
}), {})

console.log(result)

Note you can use object destructuring to simplify the accumulation code.

about 3 years ago · Juan Pablo Isaza Report

0

const data=[
  {
name: "abc",
value: "1"
  },
  {
name: "xyz",
value: "2"
  },
  {
name: "abc",
value: "3"
  },
  {
name: "abc",
value: "4"
  },
  {
name: "xyz",
value: "5"
  },
];

const res=data.reduce((a,c)=>{
 (a[c.name]??=[]).push(c.value);
 return a;
},{});
console.log(res);

about 3 years ago · Juan Pablo Isaza Report

0

const data = [{
    name: "abc",
    value: "1"
  },
  {
    name: "xyz",
    value: "2"
  },
  {
    name: "abc",
    value: "3"
  },
  {
    name: "abc",
    value: "4"
  },
  {
    name: "xyz",
    value: "5"
  },
];

let finalObject = {};

data.forEach((item) => {
   if (!finalObject.hasOwnProperty(item.name)) {
      finalObject[item.name] = [item.value];
   } else {
      finalObject[item.name].push(item.value);
   }
});
console.log(finalObject);

Just parse values if you need in string to number and it will give you answer

{
  abc: [1, 3, 4],
  xyz: [2, 5]
}
about 3 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 Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error