Ankur Bawiskar
Tera Patron
Options
- Post History
- Subscribe to RSS Feed
- Mark as New
- Mark as Read
- Bookmark
- Subscribe
- Printer Friendly Page
- Report Inappropriate Content
on 12-10-2024 09:02 PM
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:
Labels:
- 699 Views