1

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...

2
  • Are you sure you're putting it correctly? That looks like an input of array with two object, with the output of array with one object. This isn't outputting an array with keys. Commented May 2, 2017 at 6:55
  • @rrd yeah looked weird to me too Commented May 2, 2017 at 6:56

1 Answer 1

3

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; }

Sign up to request clarification or add additional context in comments.

3 Comments

@AsadAliKhan glad that helped! :)
One more help how to change [{0: "1", 1: "2"}] to ["1","2"]
@AsadAliKhan sure, hard to explain here in comments.. can you put up a new question.. you can send the question link here if you want.. this way if I can't find a solution, at least someone else will

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.