简体   繁体   中英

How do I check if an object is within an array in Javascript?

I am getting stuck on a project where I am trying to pull out relevant data from a super massive Google Maps Timeline json, and running into the problem of the structure not being as orderly as I thought it was. Essentially, I am trying to pull out an address, time, date and mileage out of this json for every trip in my car. to use this data, I pasted it into a normal javascript file and named it so I can use it as an object. I then take this data and create a string that will format that info like a CSV file.

From going over the structure of the json by looking at only a few trips, I was able to determine the following general structure:

const google = {
   timelineObjects: [
      0: {activitySegment: {A NUMBER OF OBJECTS}},
      1: {placeVisit : {A NUMBER OF OBJECTS}},
      2: {activitySegment: {A NUMBER OF OBJECTS}},
      3: {placeVisit : {A NUMBER OF OBJECTS}}
   ]
}

activitySegment has all the travelling info, like distance, travel times, etc. placeVisit has info about the destination. In my small sample, I was able to just loop through each using an if statement with i%2=0, and just change what I wanted to pull out from each, which worked well.

When I tried adding a larger sample, I was finding that Google occasionally did not create a activitySegment object and only had a placeVisit, which was throwing "Uncaught TypeError: Cannot read property 'distance' of undefined".

I am sure that the even/odd sorting will not work out any more. Is there a way to use a conditional to show if google[timelineObjects][i] is either a {activitySegment} or {placeVisit}? Or, is there a better way to figuring out what object is next in the array?

You can test to see if the Object at the particular array index has a given property using Object.prototype.hasOwnProperty() :

 const google = { timelineObjects: [ {activitySegment: {}}, {placeVisit: {}}, {activitySegment: {}}, {placeVisit: {}} ] }; console.log(google.timelineObjects[0].hasOwnProperty("activitySegment")); // true console.log(google.timelineObjects[1].hasOwnProperty("activitySegment")); // false

If your objective to see what type of object you get. You can iterate over each object, see what the key of the object is and process the data depending on the key value. Something like this.

Object.entries(google).forEach(([key, value]) => {
   if(key==='activitySegment') {
     //process activeSegment here   
   }else {
     //process placeVisit here
   }
})

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