📌  相关文章
📜  如何合并对象站点数组中的重复值:stackoverflow.com - Javascript 代码示例

📅  最后修改于: 2022-03-11 15:02:07.005000             🧑  作者: Mango

代码示例1
var myArray = [
    {productId: 116605, productserialno: "324234"},
    {productId: 106290, productserialno: "12121"},
    {productId: 106290, productserialno: "12121"},
    {productId: 106293, productserialno: "4324343"}
];

var grouped = myArray.reduce(function (obj, product) {
    obj[product.productId] = obj[product.productId] || [];
    obj[product.productId].push(product.productserialno);
    return obj;
}, {});

var groups = Object.keys(grouped).map(function (key) {
    return {product: key, productserialno: grouped[key]};
});

var pre = document.createElement("pre");
pre.innerHTML = JSON.stringify(groups, null, 4);
document.body.appendChild(pre);