Home > Net >  how to filter nested objects based on properties
how to filter nested objects based on properties

Time:08-22

Below is a nested array of objects, how can I filter this based on object property? ex. if name==="same" then it should return that object

const arrNestedObj=[
          {
            "id":"1",
            0:{
              "name":"john",
              "age":"10"
            },
            1:{
              "name":"sam",
              "age":"20"
            }
          },{ 
            "id":"2",
            0:{
              "name":"sam",
              "age":"15"
            },
          }
        ]
expected output:
if name==="same" then it should return that object
[
  {
    "name":"sam",
    "age":"20"
  },
  {
     "name":"sam",
     "age":"15"
   }
]

CodePudding user response:

If your meaning is that you want the name === 'sam' object, then can use Array.prototype.map() and Object.getOwnPropertyNames
These two method can help you to get the objects.

example:

<script>
const arrNestedObj=[
          {
            "id":"1",
            0:{
              "name":"john",
              "age":"10"
            },
            1:{
              "name":"sam",
              "age":"20"
            }
          },{ 
            "id":"2",
            0:{
              "name":"sam",
              "age":"15"
            },
          }
        ]

let result = [];
arrNestedObj.map((item) => {
  let tempArray = Object.getOwnPropertyNames(item)
    for(let i=0; i<tempArray.length-1; i  )
    {
     if(Number(tempArray[i] !== NaN))
     {
       if(item[tempArray[i]].name === "sam")
       {
        result.push(item[tempArray[i]]);
       }
     }
    }
});

console.log(result)
</script>

CodePudding user response:

Here is my solution

const output = data.map(i=>Object.values(i).filter(v=>v.name==="sam")).reduce((holder, cur)=>{
    return [...holder,...cur]
},[])

CodePudding user response:

Use the Array.prototype.filter method.

const filteredArr = arrNestedObj.filter(elem => elem.name === "sam")
  • Related