[英]Clone object based on property javascript
I'm getting a group of objects in JSON like so 我正在像这样在JSON中获得一组对象
[
{ name: "Doc 1",
product: ["product 1", "product 2"],
type: ["type 1", "type 2"]
},
{ name: "Doc 2",
product: ["product 1"],
type: ["type 1"]
},
{ name: "Doc 3",
product: ["product 2"],
type: ["type 2"]
}
...
]
I need to first clone the object for each product of the object (so I'd have 2 instances of Doc 1
) and then I want to group the objects based on the product (that would give me another 2 objects) and then grouped based on the type which would give me another 2. 我需要首先为对象的每个产品克隆对象(因此我将有2个
Doc 1
实例),然后我要根据产品对对象进行分组(这将给我另外2个对象),然后根据分组会给我另外2。
Initially we were just grouping based on the product but we then found our docs had multiple products associated with it and so we need to transform the original. 最初,我们只是基于产品进行分组,但是随后我们发现我们的文档具有与之相关的多个产品,因此我们需要转换原始产品。
How would I clone each card to a new array for each product? 如何将每个产品的每张卡克隆到新阵列?
It's anticipated that the final group of objects would look like in this simple instance, Doc 1 is the only duplicate as it's associated with product 1 and 2. 可以预料,在这个简单的实例中,最终的对象组看起来像是Doc 1是唯一的副本,因为它与产品1和2相关联。
[
{ name: "Doc 1",
product: ["product 1", "product 2"],
type: ["type 1", "type 2"]
},
{ name: "Doc 1",
product: ["product 1", "product 2"],
type: ["type 1", "type 2"]
},
{ name: "Doc 2",
product: ["product 1"],
type: ["type 1"]
},
{ name: "Doc 3",
product: ["product 2"],
type: ["type 2"]
}
...
]
You can use Object.assign
to clone the object and [].concat(yourArray)
to clone an array of primitives. 您可以使用
Object.assign
克隆对象,并使用[].concat(yourArray)
元数组。
var docs = [ { name: "Doc 1", product: ["product 1", "product 2"], type: ["type 1", "type 2"] }, { name: "Doc 2", product: ["product 1"], type: ["type 1"] }, { name: "Doc 3", product: ["product 2"], type: ["type 2"] } ] var cloned = docs.map(function (c) { // This will not clone the product c = Object.assign({}, c); // Clone the product array c.product = [].concat(c.product); return c; }); // Group by products var byProduct = { /* "product 1": [...] */ }; cloned.forEach(function (c) { c.product.forEach(function (prod) { var groupedDocs = byProduct[prod] = byProduct[prod] || []; groupedDocs.push(c); }); }); console.log(byProduct);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.