【问题标题】:Js get Objects from Array Objects, by property in nested ArrayJs通过嵌套数组中的属性从数组对象中获取对象
【发布时间】:2021-02-10 13:18:06
【问题描述】:

如何在嵌套对象中按嵌套数组tagList === 'new' 中的属性过滤此数组。

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

我想用Objects.tagList === new 获取新数组。

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

试试这个

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

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

获取空数组

【问题讨论】:

标签: javascript arrays sorting array-filter


【解决方案1】:

我不确定您是否复制粘贴了代码,但输入数组定义遗漏了一些逗号,从而导致语法错误。修复您的代码按预期工作。即

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)

将包含两个项目的数组记录到控制台。参见https://jsfiddle.net/oxra0j9w/的小提琴

【讨论】:

    猜你喜欢
    • 2013-10-11
    • 2021-10-27
    • 1970-01-01
    • 1970-01-01
    • 2018-01-16
    • 2021-07-08
    • 2021-10-29
    • 2012-11-17
    • 2019-01-12
    相关资源
    最近更新 更多