简体   繁体   中英

How to search through an array of objects inside a JSON object for a string and return the object that contains it?

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": {},
                ...
            }]
        }
    }
}

Finally got this working with the following function:

function ContainsKeyValue(obj, key, value) {
    if (obj[key] === value) return true;
    for (all in obj) {
        if (obj[all] != null && obj[all][key] === value) {
            return true;
        }
        if (typeof obj[all] == "object" && obj[all] != null) {
            var found = ContainsKeyValue(obj[all], key, value);
            if (found == true) return true;
        }
    }
    return false;
}
for (var eventType in historyDates) {
    for (var i = 0; i < trackingDetails.length; i++) {
        var detail = trackingDetails[i];
        if (ContainsKeyValue(detail, "#text", eventType)) {
            historyDates[eventType] = detail.EventDate["#text"];
        }
    }
}

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