Last active
August 4, 2018 00:06
-
-
Save unyo/7e9c49b91d5f7c58a9931f376177f679 to your computer and use it in GitHub Desktop.
Get and Set Nested Data in an Array
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
// # setNestedData | |
export function setNestedData(root, path, value) { | |
var paths = path.split('.'); | |
var last_index = paths.length - 1; | |
paths.forEach(function(key, index) { | |
if (!(key in root)) root[key] = {}; | |
if (index==last_index) root[key] = value; | |
root = root[key]; | |
}); | |
return root; | |
} | |
// ## usage | |
var obj = {'existing': 'value'}; | |
setNestedData(obj, 'animal.fish.pet', 'derp'); | |
setNestedData(obj, 'animal.cat.pet', 'musubi'); | |
console.log(JSON.stringify(obj)); | |
// {"existing":"value","animal":{"fish":{"pet":"derp"},"cat":{"pet":"musubi"}}} | |
// # getNestedData | |
export function getNestedData(obj, path) { | |
var index = function(obj, i) { return obj && obj[i]; }; | |
return path.split('.').reduce(index, obj); | |
} | |
// ## usage | |
getNestedData(obj, 'animal.cat.pet') | |
// "musubi" | |
getNestedData(obj, 'animal.dog.pet') | |
// undefined | |
// # flattenNestedData | |
export function flattenNestedData(obj) { | |
var returnObj = {}; | |
for (var i in obj) { | |
if (!obj.hasOwnProperty(i)) continue; | |
if ((typeof obj[i]) === 'object') { | |
var flatObject = flattenNestedData(obj[i]); | |
for (var x in flatObject) { | |
if (!flatObject.hasOwnProperty(x)) continue; | |
returnObj[i + '.' + x] = flatObject[x]; | |
} | |
continue; | |
} | |
returnObj[i] = obj[i]; | |
} | |
return returnObj; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment