[英]Creating array of objects with specific key taken out of appended object
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
数组中,使它们如下所示:
{
"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.这不完全是我想要实现的目标。
You don't need the object {product1}
.您不需要 object
{product1}
。 product1
is already an object, you don't have to wrap it inside another object. product1
已经是 object,您不必将其包装在另一个 object 中。
You don't need the spread operator, use the push()
method to add to an array.您不需要扩展运算符,使用
push()
方法添加到数组。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.