Last active
September 4, 2018 05:07
-
-
Save miklund/4def343a5938c13c9af4d7bb353857c0 to your computer and use it in GitHub Desktop.
2018-09-02 Recursively search and update a json javascript object
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Title: Recursively search and update a json javascript object | |
# Author: Mikael Lundin | |
# Date: 2018-09-02 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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