Asad Ali Khan
Asad Ali Khan

Reputation: 307

Joining all object of one array into same array as per key

I have this

[{"n1":{"0":"2"},"f1":{"0":3}},{"n1":{"1":"3"},"f1":{"1":2}}]

I want this

[{"n1":{"0":"2", "1":"3"},"f1":{"0":3, "1":2}}]

using underscore or Jquery.. Please guide...

Upvotes: 1

Views: 58

Answers (1)

tanmay
tanmay

Reputation: 7911

You could pull this out with pure JS using the ultimate reduce (I fondly call it one-function army) and a bunch of for-ins. Something like this:

let arr = [{"n1":{"0":"2"},"f1":{"0":3}},{"n1":{"1":"3"},"f1":{"1":2}}]

let modified = arr.reduce((res, objs) => {
  for (let key in objs) {
    res[key] = res[key] || {}
    for (let i in objs[key]) {
      res[key][i] = objs[key][i]
    }
  }
  return res
}, {})

let result = [modified]

console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 3

Related Questions