Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save miklund/4def343a5938c13c9af4d7bb353857c0 to your computer and use it in GitHub Desktop.
Save miklund/4def343a5938c13c9af4d7bb353857c0 to your computer and use it in GitHub Desktop.
2018-09-02 Recursively search and update a json javascript object
# Title: Recursively search and update a json javascript object
# Author: Mikael Lundin
# Date: 2018-09-02
// findObjectById: helper function
// comment: will recurse through an object graph, looking for matching Id's and run the update function
const findObjectById = (obj, id, updateFn) => {
// have found the object
if (obj["Id"] === id) {
return updateFn(obj);
}
else {
// iterate over the properties
for (var propertyName in obj) {
// any object that is not a simple value
if (obj[propertyName] !== null && typeof obj[propertyName] === 'object') {
// recurse into the object and write back the result to the object graph
obj[propertyName] = findObjectById(obj[propertyName], id, updateFn);
}
}
}
return obj;
};
var animals = {
anything {
ID = '123',
Name = {
'en': 'Phoney Pony'
}
}
};
var updateFn = obj => {
obj.Name['sv-SE'] = 'Fånig ponny'
};
var result = findObjectById(animals, '123', updateFn);
// the result will look like this
// var animals = {
// anything {
// ID = '123',
// Name = {
// 'en': 'Phoney Pony',
// 'sv-SE': 'Fånig ponny'
// }
// }
// };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment