简体   繁体   中英

How to filter a nested, nested object in JavaScript?

I have this 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"
           }],
        },]
     } 
  },
 ]
}

I want to get only the objects where there is the value "Problem 1". Right now I have this structure in an Array with 641 player objects to check and only bring the one with "Problem 1".

Added a solution to the problem, you are highly dependent on the data structure, and if it changes the solution will need to be altered.

 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)

Think about it. It's actually quite simple.

I assume this will ultimately become a JSON structure. With that in mind, the problem is that in JSON you can't go upwards from child to parent; you can only go downwards from parent to child.

Therefore, you need really only to iterate through the data object and look at each player object. For each player object, check if properties.favoriteColour contains the item "Problem 1" . If it does, note the other attributes you want of that player object, or copy it altogether to store somewhere, depending what you ultimately want to do with it.

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