简体   繁体   中英

How to filter array and create new array with specific object keys

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"
     }
  ]
  }
]

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

vanilla JS 中的单行(早于 EMCAScript 2019,flatMap 不可用,所以在这种情况下......)

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM