Skip to content

Instantly share code, notes, and snippets.

@riverspirit
Created August 20, 2013 04:24
Show Gist options
  • Save riverspirit/6277099 to your computer and use it in GitHub Desktop.
Save riverspirit/6277099 to your computer and use it in GitHub Desktop.
From nested JSON data, get the parent node when a 'value' (not key) is provided.
var jsondata = {
'name': {
'fname': 'Jack',
'lname': [
{'familyName': 'Sparrow'},
{'surname': 'Captain'},
{'tags':[
{'test': 'mocha'},
'program',
{'level': 'five',}
]}
]
}
};
var result = get_parent_node(jsondata, 'five');
console.log(result);
function get_parent_node(dataObject, searchKey) {
var parentRef = dataObject;
var parent = null;
this.get_parent = function (dataObject, searchKey) {
for (i in dataObject) {
if (dataObject[i] == searchKey) {
parent = parentRef;
} else if (typeof dataObject[i] == 'object') {
parentRef = dataObject;
this.get_parent(dataObject[i], searchKey);
}
}
}
this.get_parent(dataObject, searchKey);
return parent;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment