繁体   English   中英

如何在 JavaScript 中过滤嵌套的嵌套 object?

[英]How to filter a nested, nested object in JavaScript?

我有这个 object:

{
  value: "something",
  data:  Array[{
     player: "simple name",
     properties: {
        age: "",
        favouriteColour: Array[{
           a: "1", 
           b: "2",
           c: Array[{
              0: "Problem 1",
              1: "Problem 2"
           }],
        },]
     } 
  },{
     player: "simple name",
     properties: {
        age: "",
        favouriteColour: Array[{
           a: "1", 
           b: "2",
           c: Array[{
              1: "Problem 2"
           }],
        },]
     } 
  },
 ]
}

我只想获取值为“问题 1”的对象。 现在我在一个包含 641 个玩家对象的数组中有这个结构要检查,并且只带一个带有“问题 1”的对象。

添加了问题的解决方案,您高度依赖数据结构,如果它发生变化,则需要更改解决方案。

 const toFilter = { value: 'something', data: [ { player: 'simple name', properties: { age: '', favouriteColour: [ { a: '1', b: '2', c: [ { 0: 'Problem 1', 1: 'Problem 2' } ] } ] } }, { player: 'simple name', properties: { age: '', favouriteColour: [ { a: '1', b: '2', c: [ { 1: 'Problem 2' } ] } ] } } ] } const filtered = toFilter.data.reduce((acc, el) => { // hightly dependand on the data structure const colors = Object.values(el.properties.favouriteColour[0].c[0]) const isValid = colors.includes('Problem 1') if (isValid) acc.push(el) return acc }, []) console.log('filtered:', filtered)

想想看。 其实很简单。

我假设这最终将成为 JSON 结构。 考虑到这一点,问题是在 JSON 你不能 go 从孩子到父母向上; 您只能从父级到子级向下 go 。

因此,您实际上只需要遍历数据 object 并查看每个播放器 object。 对于每个玩家 object,检查properties.favoriteColour是否包含项目"Problem 1" 如果是这样,请记下您想要该播放器 object 的其他属性,或者将其完全复制到某个位置,具体取决于您最终想要用它做什么。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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