Home > Mobile >  How to check nested JSON property and value exist in JavaScript?
How to check nested JSON property and value exist in JavaScript?

Time:09-07

I am getting below JSON as API response. Response contains multiple session node, each session node contains multiple event node. I would like to identify the first "SEARCH" event ("type") in any of the session ascending. If the "SEARCH" event is found, then, from the particular event, I need to get the "Interest" node value.

var guestJson = await response.json(); 
           for(var property in guestJson)
           {                    
                if(property === "sessions")
                {                         
                     var sessionObj = JSON.parse(JSON.stringify(guestJson[property]))
                     for(var i=0; i< sessionObj.length; i  )
                     {   
                          var eachSessionObj = JSON.parse(JSON.stringify(sessionObj[i]))  
                          
                          for(var sessionProperty in eachSessionObj)                
                          {                                   
                               if(sessionProperty === "events")
                               {
                                    console.log("Events Found")
                                    //console.log(sessionProperty)
                               }
                          }                              
                     }
                }                  
           }

I am able to do with for loop like below. But i think it's not the effective way of doing that

Below is the JSON structure

{
     "firstName":"fn",
     "lastName":"ln",
     "gender":"male",
     "sessions":[
  {
     "currency":"USD",
     "events":[
        {
           "type":"SEARCH",
           "status":"PROCESSED",
           "arbitraryData":{
              "interest":"Health"
           }
        },
        {
           "type":"CHECK",
           "status":"PROCESSED",
           "arbitraryData":{
              "interest":"Dental"
           }
        }
     ]
  },
  {
     "currency":"USD",
     "events":[
        {
           "type":"SEARCH",
           "status":"PROCESSED",
           "arbitraryData":{
              "interest":"Health"
           }
        },
        {
           "type":"CHECK",
           "status":"PROCESSED",
           "arbitraryData":{
              "interest":"Dental"
           }
        }
     ]
  }

] }

CodePudding user response:

You could try a function like this:

function extractInterest(guestJson) {
    // Get all sessions or else get an empty array
    const sessions = guestJson.sessions || [];

    // Filter all sessions with events
    const interest = sessions.filter(session => session.events)
        .flatMap(session => session.events) // Maps all the events to a single list
        .filter(event => event.type === "SEARCH") // Filter only the events with type "SEARCH"
        .map(event => event.arbitraryData.interest); // Extract the interest from each event

    return interest; // return the list of interests
}

When applied to your example JSON, this returns an array of interests like this:

[ 'Health', 'Health' ]

  • Related