简体   繁体   English

使用从附加的 object 中取出的特定键创建对象数组

[英]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.

相关问题 从没有特定键值的 Object 创建对象数组 - Creating An Array of Objects From An Object Without Specific Key Values 从对象数组创建一个新对象,并按特定的匹配键/值分组 - Creating a new object from array of objects and grouping by specific matching key/value Javascript从该数组中附加对象并创建附加了对象键值对的新数组 - Javascript Append objects from this array and create new array with object key value pairs appended 使用特定的JSON键值对创建数组 - Creating an array out of a specific JSON Key-Value Pair 创建对象数组后如何更新 object 的键值? JavaScript - After creating array of objects how to update a key value of object? JavaScript 如何基于键搜索充满对象的数组并返回特定对象 - how to search an array full of objects based on a key and return a specific object 如何连接对象数组中的值-对象中的特定键 - How to connect values in array of objects - a specific key in the object 如何从具有特定键值的对象数组中获取 object? - How to get an object from an array of objects with a specific value for a key? 检查对象数组中是否存在具有特定键值的对象 - check if an object with a specific key value exists in an array of objects 从 object 中提取键值到具有特定字段的对象数组中 - Extracting key value from object into array of objects with specific fields
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM