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

97
Views
Merge all keys into single object with the same Id in JavaScript

I have an array of objects Like that.

var orderResults = [{
    id: '1',
    name: 'Maya Mahardhani',
    payment_amount : 100,
    sku: 'ST001802027',
    seq: '1'
},
{
    id: '1',
    name: 'Maya Mahardhani',
    payment_amount : 50,
    sku: 'ST000703044',
    seq: '2'
},
{
    id: '2',
    name: 'Tara Debu Batara',
    payment_amount : 100,
    sku: 'ST005101001',
    seq: '1'
},
{
    id: '3',
    name: 'Nikita Gigir',
    payment_amount : 100,
    sku: 'ST004403030',
    seq: '1'
}]

But I am trying to extract the data in the following way.

[{
    id: '1',
    name: 'Maya Mahardhani',
    total_amount : 150,
    sku_1: 'ST001802027',
    sku_2: 'ST000703044',
},
{
    id: '2',
    name: 'Tara Debu Batara',
    total_amount : 100,
    sku_1: 'ST005101001'
},
{
    id: '3',
    name: 'Nikita Gigir',
    total_amount : 100,
    sku_1: 'ST004403030'
}]

I give try with the reduce function of JavaScript. But it overwrites the prev key with the old one. My Code Snippet is like that. I think I am closer to solve. But still seeking the help

orderResults.reduce((res, obj) => {
    res[obj.id] = { 
        total_amount : (obj.id in res ? res[obj.id].total_amount : 0)  + obj.payment_amount,
        name : obj.name,
    }

    res[obj.id]['sku' + obj.seq]= obj.sku
    return res;
},[])

Thank you

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

0

I think this will do what you are trying to do:

orderResults.reduce((res, obj, i) => {
    const existingIdx = res.findIndex(r => r.id === obj.id)
    if (existingIdx > -1) {
      res[existingIdx] = { 
        ...res[existingIdx],
        total_amount : res[existingIdx].total_amount ? res[existingIdx].total_amount + obj.payment_amount : res[existingIdx].payment_amount + obj.payment_amount,
        name : obj.name,
        ['sku_' + obj.seq]: obj.sku
      }
    } else {
      res.push({
        id: obj.id,
        name: obj.name,
        total_amount: obj.payment_amount,
        ['sku_' + obj.seq]: obj.sku
      })
    }

    return res;
},[])

Notice this line will preserve the original object and overwrite any duplicate keys that are defined afterwards:

...res[existingIdx],

Also when your code runs this line:

res[obj.id] = {

it is setting a specific index in the array, which I don't think you want to do. You want to either push (if the object id hasn't been added yet), or overwrite the existing object at the original insertion point when the object with the same id was created.

about 4 years ago · Juan Pablo Isaza Report

0

Do not create a new object every time.

const result = Object.values(orderResults.reduce((res, obj) => {
    res[obj.id] = res[obj.id] ||
    {   
        id: obj.id,
        total_amount : 0,
        name : obj.name,
    };
    res[obj.id].total_amount += obj.total_amount;
    res[obj.id]['sku' + obj.seq] = obj.sku;
    return res;
},[]))
about 4 years ago · Juan Pablo Isaza Report

0

[{
    id: '1',
    name: 'Maya Mahardhani',
    payment_amount: 100,
    sku: 'ST001802027',
    seq: '1'
},
{
    id: '1',
    name: 'Maya Mahardhani',
    payment_amount: 50,
    sku: 'ST000703044',
    seq: '2'
},
{
    id: '2',
    name: 'Tara Debu Batara',
    payment_amount: 100,
    sku: 'ST005101001',
    seq: '1'
},
{
    id: '3',
    name: 'Nikita Gigir',
    payment_amount: 100,
    sku: 'ST004403030',
    seq: '1'
}].reduce((acc, current) => {
    const { id, name, payment_amount, sku, seq } = current;
    const previousRecord = acc[id];
    if (typeof previousRecord === 'object') {
        return {
            ...acc,
            [id]: {
                ...previousRecord,
                [`sku_${seq}`]: sku,
                total_amount: previousRecord.total_amount + payment_amount
            }
        }
    } else {

        return {
            ...acc,
            [id]: {
                id,
                name,
                [`sku_${seq}`]: sku,
                total_amount: payment_amount
            }
        }
    }
}, {}) // returns an Object; use Object.values to convert to a list
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!