Skip to content
Advertisement

Merge 2 objects in an array where the values are an array

I am trying to merge values in 2 objects from the same array. The objects in this case are similar and the values I want to merge are arrays(Set)

var array = [
  {
  name: "foo1",
  value: ["val1","val2"]
}, 
{
  name: "foo1",
  value: ["val2", "val3"]
}, 
{
  name: "foo2",
  value: ["val4"]
},
 {
  name: "foo2",
  value: ["val4","val5"]
},
];

Expected Output

[
{
  name: "foo1",
  value: ["val1","val2", "val3"]
},{
  name: "foo2",
  value: ["val4","val4", "val5"]
}
]

My Code

var output = [];

array.forEach(function(item) {
  var existing = output.filter(function(v, i) {
    return v.name == item.name;
  });
  if (existing.length) {
    var existingIndex = output.indexOf(existing[0]);
    let newValue = new Set(output[existingIndex].value).add(item.value)
    output[existingIndex].value = Array.from(newValue);
  } else {
    output.push(item);
  }
});

Output Gotten

[ {
  name: "foo1",
  value: ["val1", "val2", ["val2", "val3"]]
}, {
  name: "foo2",
  value: ["val4", ["val4", "val5"]]
}]

How can I get the expected output (ES6 would also be preferred)

Advertisement

Answer

Try this

const array = [
  {
    "name": "foo1",
    "value": [
      "val1",
      "val2",
      "val3"
    ]
  },
  {
    "name": "foo1",
    "value": [
      "val2",
      "val3"
    ]
  },
  {
    "name": "foo2",
    "value": [
      "val4",
      "val5"
    ]
  },
  {
    "name": "foo2",
    "value": [
      "val4",
      "val5"
    ]
  }
]

const result = []

for (const item of array) {
  const existingItem = result.find(i => i.name === item.name)
  if (existingItem) {
    existingItem.value = [...new Set([...existingItem.value, ...item.value])]
  } else {
    result.push(item)
  }
}

console.log(result)
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement