0

Generate an array of objects in a format from an array of objects inside another array .

The Given array is :

let target =
[[{key: "subscriber_id", value: "1"},
{key: "msisdn_value", value: "2"}],
[{key: "subscriber_id", value: "3"},
{key: "msisdn_value", value: "4"}
]]

The expected array of objects should be :

result = [
  {"subscriber_id":"1","msisdn_value":"2"},
  {"subscriber_id":"3","msisdn_value":"4"},
]
1
  • 1
    Please paste your current code implementation Commented Aug 24, 2019 at 9:17

2 Answers 2

3

Use nested map calls with Object.fromEntries and Object.values for a clean and concise solution like so:

const result = target.map(e => Object.fromEntries(e.map(Object.values)));

Or, for a more efficient solution, use reduce:

const result = target.map(e => e.reduce((a, { key, value }) => (a[key] = value, a), {}));
Sign up to request clarification or add additional context in comments.

Comments

2

You can use map and destructuring

let target = [[{key: "subscriber_id",value: "1"},{key: "msisdn_value",value: "2"}],[{key: "subscriber_id",value: "3"},{key: "msisdn_value",value: "4"}]]

let final = target.map(data => {
  let [{key:a,value:b},{key:c,value:d}] = data
  return { [a]:b, [c]:d }
})

console.log(final)

Loop through each element if there are more than two elements in inner arrays

let target = [[{key: "subscriber_id",value: "1"},{key: "msisdn_value",value: "2"}],[{key: "subscriber_id",value: "3"},{key: "msisdn_value",value: "4"},{key: "key",value: "value"}]]

let final = target.map((data) => {
  return data.reduce((obj,{key,value})=>{
    obj[key] = value 
    return obj
  },{})
})

console.log(final)

1 Comment

What if there's more than two key/value pairs? Nobody wants to copy/paste more code, and it'll be extremely WET. reduce is better in this case.

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.