The Problem
The method to search through a JSOn Object that I found in this SO answer works well, however, I need it to return the "object that contains the matched object, value or pair" rather than the matched object itself.
The Code
function getObjects(obj, key, val) {
var objects = [];
for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
if (typeof obj[i] == 'object') {
objects = objects.concat(getObjects(obj[i], key, val));
} else if (i == key && obj[key] == val) {
objects.push(obj);
}
}
return objects;
}
getObjects(obj, key, val);
The Question
How can I augment that to return the object that contains the matched object/value/pair instead of just the match itself? (jQuery or JS)
JSON Sample
For example, I need to check if the value "Delivered, Front Door/Porch" of key Event
(or Event[#text]
) exists, and if so, I need to find the EventDate
in that object in which the Event
was found.
{
"TrackResponse": {
"TrackInfo": {
"@attributes": {
"ID": "9470111699000308312927"
},
"GuaranteedDeliveryDate": {
"#text": "September 9, 2015"
},
"TrackSummary": {
"EventTime": {
"#text": "2:06 pm"
},
"EventDate": {
"#text": "September 10, 2015"
},
"Event": {
"#text": "Delivered, Front Door/Porch"
},
...
},
"TrackDetail": [{
"EventTime": {
"#text": "8:07 am"
},
...
}, ... {
"EventTime": {},
...
}]
}
}
}