1

I have an array with objects and in each object there is an "items" array. My goal is to combine these "items" into one array.

Goal / Expected Output

[
   { id: 'SUV' },
   { id: 'Compact' },
   { id: 'Gasoline' },
   { id: 'Hybrid' }
]

Sample Array

[
{
  "id":"carType",
  "items":[
     {
        "id":"SUV"
     },
     {
        "id":"Compact"
     }
  ]
},
{
  "id":"fuelType",
  "items":[
     {
        "id":"Gasoline"
     },
     {
        "id":"Hybrid"
     }
  ]
  }
]
0

3 Answers 3

5

You could use Array#flatMap.

const data = [{"id":"carType","items":[{"id":"SUV"},{"id":"Compact"}]},{"id":"fuelType","items":[{"id":"Gasoline"},{"id":"Hybrid"}]}];

const r = data.flatMap(({ items }) => items);

console.log(r);

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

Comments

3

A one-liner in vanilla JS (earlier than EMCAScript 2019, flatMap is not available, so in case of that...)

[].concat(...arr.map(elt => elt.items))

Comments

0

Something like this?

newArr = []
for (let i = 0;i<arr.length;i++) {
  for (let ii = 0;ii<arr[i].items.length;ii++) {
    newArr.push(arr[i].items[ii].id)
  }
}
console.log(newArr)

Comments

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.