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

177
Views
Combine values from an array of objects on the basis of key name

const input = [{car: 'BMW' }, {car: 'Benz'}, {bike: 'KTM'}, {bike: 'Honda'}]

const output = {car: ['BMW','Benz'], bike: ['KTM','Honda']}

Is this possible?

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

0

group by problems can be solved using reduce. Here I assumed that each element in the input array has only 1 key value pair

const input = [{car: 'BMW' }, {car: 'Benz'}, {bike: 'KTM'}, {bike: 'Honda'}]

const output = input.reduce((acc,curr)=>{
      const [k,v] = Object.entries(curr)[0]
      acc[k] = acc[k] || []
      acc[k].push(v)
      return acc
},{})

console.log(output)

about 4 years ago · Juan Pablo Isaza Report

0

It's pretty simple - Loop over the array of objects, check if the key exists in output object if not - create key with value - array and push the value else just push the value to existing key.

const input = [{car: 'BMW' }, {car: 'Benz'}, {bike: 'KTM'}, {bike: 'Honda'}]
let output = {};
for(let i = 0 ; i < input.length ; i++){
    const key = Object.keys(input[i])[0];
    if(!output[key]){
        output[key] = [input[i][key]];
    }else{
        output[key].push(input[i][key])
    }
}
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!