Search code examples
reactjspropertieshierarchy

How to select all objects in nested hierarchy by property in react application?


I hope I haven't overlooked a similar question. I think it should be really easy, but I can't find an approach.

I've got an an array filled with objects, the length of the array can differ in every timestamp. Like in the picture: array with 12 Objects and properties "id", "quality"..

I am now looking for a simple method to see if the properties of "id" and "quality" are defined by now. For example: I can test the type of the first objects property using:

typeof this.state.net["links"][0]["id"].

I am looking for something like this:

typeof this.state.net["links"][#]["id"] 

where "#" selects all values with the property "id" and allows me to see if every property is defined with an string, without using a loop. Thanks and salute :)


Solution

  • Using lodash for this case is perfect fit, your code to check it looks like

    import _ from 'lodash'
    
    if (_.every(this.state.net.links, data => typeof data.id === 'string')) {
      // Your logic code
    }
    

    Actually, lodash uses a loop, but the code is very elegant.