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

181
Views
Merging the contents of my array into one object

I have an array of several objects

array1 =[ {1:Eat},{2:Shower},{3:Shave}]

I want to convert this array into a single object

object1 ={1:Eat, 2:Shower, 3:Shave}

How do I go about it. The keys(1,2,3) are unique

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

THE SOLUTION

array.reduce((a, v) => Object.assign(a,v), {})

THE EXPLANATION

Array.reduce() loops throw the initial array aimed to "reduce" it into a single object. The reduce method allows you to store the return value of each of your iterations. It requires an initial value which in this case it will be the empty object {} that we will be filling up with our array.

Then we use Object.assign(target, source) which concatenates two objects together returning the concatenated object which in this case it will saved into our accumulator and be used as a target for the next iteration giving you when it finishes the constructed final object. As you have objects as the keys of the array, each single property Object(source) will be "assigned" to a master one (target) that will be collecting all of them into one.

array1 =[ {1:'Eat'},{2:'Shower'},{3:'Shave'}]
obj1 = array1.reduce((a, v) => Object.assign(a,v), {})
console.log(obj1)

about 4 years ago · Juan Pablo Isaza Report

0

The easiest way to achieve this is to reduce the list of objects into a single object.

const
  input = [{ 1: 'Eat' }, { 2: 'Shower' }, { 3: 'Shave' }],
  output = input.reduce((acc, obj) => ({ ...acc, ...obj }), {});

console.log(output);
.as-console-wrapper { top: 0; max-height: 100% !important; }

about 4 years ago · Juan Pablo Isaza Report

0

fromEntries and a flatMap seems to do the trick nicely

const array1 = [ {1:'Eat'},{2:'Shower'},{3:'Shave'}]
const obj1 = Object.fromEntries(array1.flatMap(item => Object.entries(item)))

console.log(obj1)

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!