Home > Software design >  Creating array of objects with specific key taken out of appended object
Creating array of objects with specific key taken out of appended object

Time:08-30

Initially, there is an empty array, and later some objects appear:

const aggregator = [];

const product1 = {"id": "prod1", "contents": {"key1": "value1"}};
const product2 = {"id": "prod2", "contents": {"key2": "value2"}};

How to add these objects to the aggregator array so that they are like:

{
    "aggregator": [
    {
        "id": "prod1",
        "contents": {
            "key1": "value1"
        }
    },
    {
        "id": "prod2",
        "contents": {
            "key2": "value2"
        }
    }
    ]
}

My approach was using the spread operator:

aggregator = [...aggregator, {product1}];
aggregator = [...aggregator, {product2}];

But that way I got something like:

console.log(JSON.stringify(aggregator));
/*
'[
{"product1":{"id":"prod1","contents":{"key1":"value1"}}},
{"product2":{"id":"prod2","contents":{"key2":"value2"}}}
]'
*/

which is not exactly something I wanted to achieve.

CodePudding user response:

You don't need the object {product1}. product1 is already an object, you don't have to wrap it inside another object.

You don't need the spread operator, use the push() method to add to an array.

const aggregator = [];

const product1 = {"id": "product1", "contents": {"key1": "value1"}};
const product2 = {"id": "product2", "contents": {"key2": "value2"}};

aggregator.push(product1);
aggregator.push(product2);
console.log(aggregator);

  • Related