简体   繁体   中英

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

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"
           }
        }
     ]
  }

] }

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' ]

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