Skip to content

Instantly share code, notes, and snippets.

@joeyklee
Created February 21, 2019 16:59
Show Gist options
  • Save joeyklee/6360cacd0c702fc4e19b737138d1c518 to your computer and use it in GitHub Desktop.
Save joeyklee/6360cacd0c702fc4e19b737138d1c518 to your computer and use it in GitHub Desktop.
An example of using recursion to update a nested json file
let myList = {
"type": "list",
"name": "Hello world",
"description": "nestednesss!",
"features": [
{
"clientId": "-ACEnpvvPe",
"type": "list",
"name": "🌈",
"description": "",
"features": [
{
"clientId": "IsfpEx4lwN",
"type": "list",
"name": "❤️1",
"description": "A list 1 description",
"features": [
{
"url": "www.itp.nyu.edu",
"name": "✨1",
"description": "Website to NYU's ITP/IMA program"
},
{
"url": "www.nautilist.github.io/",
"name": "✨2",
"description": "Nautilist is a tool for ..."
}
]
},
{
"clientId": "XJx3F-a1g7",
"type": "list",
"name": "❤️2",
"description": "A list 2 description",
"features": [
{
"url": "www.itp.nyu.edu",
"name": "🌴1",
"description": "Website to NYU's ITP/IMA program"
},
{
"url": "www.nautilist.github.io/",
"name": "🌴2",
"description": "Nautilist is a tool for ..."
}
]
}
]
}
],
"clientId": "rT-b5USQ1k"
}
// console.log(myList);
let updatedList = findRecursive(myList, 'IsfpEx4lwN');
moveVal(updatedList.features, 1, 0);
updateMain(myList, updatedList, 'IsfpEx4lwN')
console.log( JSON.stringify(myList) )
// helper functions
function moveVal(arr, from, to) {
arr.splice(to, 0, arr.splice(from, 1)[0]);
};
function updateMain(_myList, _updatedList, _parentId){
// update the data directly here!
if(_myList.clientId === _parentId){
_myList = _updatedList
return updatedList
}
let p;
for(p in _myList){
if(_myList.hasOwnProperty(p) && typeof _myList[p] === 'object'){
_myList = updateMain(_myList[p], _updatedList, _parentId);
if(_myList){
return _myList
}
}
}
return _myList
}
function findRecursive(_myList, _parentId){
const listCopy = Object.assign({}, _myList);
let result;
let p;
// early return
if(listCopy.clientId === _parentId){
return listCopy;
}
for(p in listCopy){
if(listCopy.hasOwnProperty(p) && typeof listCopy[p] === 'object'){
result = findRecursive(listCopy[p], _parentId);
if(result){
return result;
}
}
}
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment