Find your people. Pick a challenge. Ship something real. The CreatorCon Hackathon is coming to the Community Pavilion for one epic night. Every skill level, every role welcome. Join us on May 5th and learn more here.

Ankur Bawiskar
Tera Patron

This is a simple function which can be called to fetch value for any unique key in simple or complex json object.

Example:

var obj = {"name":"Chris","age":23,"address":{"city":"New York","country":"America"},"friends":[{"name":"Emily","hobbies":["biking","music","gaming"]},{"name":"John","hobbies":["soccer","gaming"]}]};
var val = getKeyValue(obj, 'city');
gs.info(val);

// this function takes the complete json object and the unique key whose value needs to be fetched
function getKeyValue(obj, key){
try {
            if (obj.hasOwnProperty(key)) {
                return obj[key];
            }
            for (var k in obj) {
                if (typeof obj[k] === 'object' && obj[k] !== null) {
                    var result = this.getKeyValue(obj[k], key);
                    if (result !== undefined) {
                        return result;
                    }
                }
            }
            return undefined;
        } catch (ex) {
            gs.info("Exception in function getKeyValue " + ex);
        }
}

Output:

AnkurBawiskar_0-1733893273001.png

 

 

Version history
Last update:
‎12-10-2024 09:02 PM
Updated by:
Contributors