-1

I need to combine object keys values from json arrays by key.

json1 = [
          {key:'xyz', value:['a','b']},
          {key:'pqrs', value:['x','y']}
        ]

json2 = [
          {key:'xyz', value:['c','b']},
          {key:'pqrs', value:['e','f']}
        ]

I need a combined object keys values in javascript in the following way

 json3 = [
              {key:'xyz', value:['a','b','c']},
              {key:'pqrs', value:['x','y','e','f']}
            ]

So, want to combine unique values on object from json arrays by key.

Mehul Mali
  • 3,084
  • 4
  • 14
  • 28

3 Answers3

1

You can use forEach() loop to add to array and Set to remove duplicates from object value.

var json1 = [{key:'xyz', value:['a','b']},{key:'pqrs', value:['x','y']}]
var json2 = [{key:'xyz', value:['c','b']},{key:'pqrs', value:['e','f']}]

var result = []
json1.concat(json2).forEach(function(e) {
  if(!this[e.key]) this[e.key] = e, result.push(this[e.key])
  else this[e.key].value = [...new Set(this[e.key].value.concat(e.value))]
}, {})

console.log(result)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
  • Should you answer a question without any effort? – Rajesh Mar 23 '17 at 10:10
  • @Nenad Vracar Is this working with this data **json1** = [{"key":"xyz","value":[{"text":"#incident/test"}]},{"key":"@abcd","value":[{"text":"2"}],"pattern":"^([0-9]|[1-9][0-9])$"}] **json2** = [{"key":"xyz","value":[{"text":"#test"}, {"text":"#incident/test"}],"check":true},{"key":"@abcd","value":[{"text":"2"}],"pattern":"^([0-9]|[1-9][0-9])$","check":true}] – Mehul Mali Mar 23 '17 at 11:06
  • 1
    You should try it. – Nenad Vracar Mar 23 '17 at 11:10
1

function combinedJson(json1, json2) {
 var ret = []
  for (let i = json1.length; i--;) {
   json2Obj = json2.find(item => item.key === json1[i].key)
   ret.push({
    key: json1[i].key,
    value: json1[i].value.concat(
     json2Obj ? json2Obj.value : []
    )
   })
  }
  return ret
}

json1 = [
  { key: 'xyz', value: ['a', 'b'] },
  { key: 'pqrs', value: ['x', 'y'] }
]

json2 = [
  { key: 'xyz', value: ['c', 'b'] },
  { key: 'pqrs', value: ['e', 'f'] }
]


console.log(combinedJson(json1, json2))
Mervyn
  • 543
  • 4
  • 15
  • Excellent. The only thing that differs from what is asked for, is that you get "b" duplicated in the second object, whereas the original poster wants just *one* "b" in their answer. – Henke Mar 18 '21 at 09:40
0

What you are looking for when joining the arrays is defined as a union (see here) in mathematics (set theory).

A similar topic regarding implementation of a union has been opened here.

Community
  • 1
  • 1
Mantas
  • 89
  • 6