将重复的对象键数组合并为单个数组

时间:2018-07-14 05:02:37

标签: javascript angular angular6

enter image description here

这是我正在寻找的愿望输出

[
    productId:106290,
    productserialno:[{
    "12121",
    "212121"
}]
]

1 个答案:

答案 0 :(得分: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);