简体   繁体   中英

Js get Objects from Array Objects, by property in nested Array

How filter this array by property in nested array tagList === 'new' in nested objects.

const myArray=[
  { 
    "name": "myItem",
    "tagList": ["hot", "new"]
  },
  { 
    "name": 'myItem2'
    "tagList": ["new"]
  },
  { 
    "name": "myItem3"
    "tagList": []
  },
]

I want get new array with Objects.tagList === new .

  { 
    "name": "myItem",
    "tagList": ["hot", "new"]
  },
  { 
    "name": 'myItem2'
    "tagList": ["new"]
  },

trying this

const newArray = myArray.filter((item) => item.tagList === 'new')

or

const newArray = myArray.filter(i => i.tagList.includes('new'))

get empty Array

I'm not sure you have copy pasted the code but the input array definition misses a few commas resulting syntax errors. Fixing that your code works as expected. Ie

const myArray=[
  { 
    "name": "myItem",
    "tagList": ["hot", "new"]
  },
  { 
    "name": 'myItem2',
    "tagList": ["new"]
  },
  { 
    "name": "myItem3",
    "tagList": []
  },
]

const newArray = myArray.filter(i => i.tagList.includes('new'))

console.log(newArray)

logs an array with two items to the console. See fiddle at https://jsfiddle.net/oxra0j9w/

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