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

100
Views
How to loop an array of objects without index as field in Javascript?

I have to arrange a list of orders, then after have the data ready, this list of objects need to be inserted in another object.

I created a simplified code for better comprehension:

const orderList = [];

orderList.push({
    order1: { desc: "smt1" }
})

orderList.push({
    order2: { desc: "smt2" }
})

const result = {
    anotherVar1: 1,
    anotherVar2: 2,
    ...orderList
}
console.log("result", result)

Output
{
    '0': { order1: { desc: 'smt1' } },
    '1': { order2: { desc: 'smt2' } },
    anotherVar1: 1,
    anotherVar2: 2,
}
Desired output:
{
    order1: { desc: 'smt1' },
    order2: { desc: 'smt2' },
    anotherVar1: 1,
    anotherVar2: 2,
}

How to achieve the desired output?

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

0

You want orderList to be an object, not an array. Then instead of using push, you want to set the key/value on the object.

const orderList = {};

orderList.order1 = { desc: "smt1" };
orderList.order2 = { desc: "smt2" };

const result = {
    anotherVar1: 1,
    anotherVar2: 2,
    ...orderList
}

console.log('result', result);

about 4 years ago · Juan Pablo Isaza Report

0

As @Rocket Hazmat mentions in his answer, use an object instead off an array


To answer the original question, you'll need to convert the array of object to an object before you can 'merge' them

const orderList = [];

orderList.push({ order1: { desc: "smt1" } });
orderList.push({ order2: { desc: "smt2" } });

const result = {
    anotherVar1: 1,
    anotherVar2: 2,
    ...Object.assign({}, ...orderList)
};

console.log('result', result);

How to convert an array of objects to object with key value pairs

about 4 years ago · Juan Pablo Isaza Report

0

As a better method keep that array as an object so that you can avoid duplication and additional looping

And as in your same method, you can follow this code to make your desired output

const orderList = [];

orderList.push({
    order1: { desc: "smt1" }
})

orderList.push({
    order2: { desc: "smt2" }
})

const result = {
    anotherVar1: 1,
    anotherVar2: 2,
}
orderList.map(d => {
  for(key in d) {
    result[key] = d[key]
  }
  
})
console.log("result", result)

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!