how to merge duplicate value in array of object site 3astackoverflow com

Solutions on MaxInterview for how to merge duplicate value in array of object site 3astackoverflow com by the best coders in the world

showing results for - "how to merge duplicate value in array of object site 3astackoverflow com"
Laura
28 Oct 2019
1var myArray = [
2    {productId: 116605, productserialno: "324234"},
3    {productId: 106290, productserialno: "12121"},
4    {productId: 106290, productserialno: "12121"},
5    {productId: 106293, productserialno: "4324343"}
6];
7
8var grouped = myArray.reduce(function (obj, product) {
9    obj[product.productId] = obj[product.productId] || [];
10    obj[product.productId].push(product.productserialno);
11    return obj;
12}, {});
13
14var groups = Object.keys(grouped).map(function (key) {
15    return {product: key, productserialno: grouped[key]};
16});
17
18var pre = document.createElement("pre");
19pre.innerHTML = JSON.stringify(groups, null, 4);
20document.body.appendChild(pre);