Home > Blockchain >  How to loop an array of objects without index as field in Javascript?
How to loop an array of objects without index as field in Javascript?

Time:10-27

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)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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?

CodePudding user response:

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)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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);
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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);
<iframe name="sif4" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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

CodePudding user response:

you can try this line without changing your code -

orderList.map((item) => (result = { ...item, ...result }));

  • Related