Skip to content

Instantly share code, notes, and snippets.

@eeropic
Created July 26, 2019 20:59
Show Gist options
  • Save eeropic/f6b968e0f9dbc1d4375f6752d8b91a35 to your computer and use it in GitHub Desktop.
Save eeropic/f6b968e0f9dbc1d4375f6752d8b91a35 to your computer and use it in GitHub Desktop.
recursive depth-first object traversal for lottie json
// modified from derick bailey https://derickbailey.com/2015/07/19/using-es6-generators-to-recursively-traverse-a-nested-data-structure/
function getType(object) {
return Object.prototype.toString.call(object)
.match(/^\[object\s(.*)\]$/)[1].toLowerCase()
}
function isArray(o) {
return getType(o) === 'array';
}
function isObject(o) {
return getType(o) === 'object';
}
let testData = {
a: 1,
b: 2,
c: [1,2,3],
d: {
x:1,
y:{
u:[1,2,3],
v:5
}
},
g: [1,2,[1,2,3]]
}
function *processData(data, depth, dataIsObject){
data = dataIsObject ? Object.entries(data) : data
for (let i = 0; i < data.length; i++){
let key = dataIsObject ? data[i][0] : i;
let val = dataIsObject ? data[i][1] : data[i];
if (isArray(val) || isObject(val)) {
yield *processData(val, ++depth, isObject(val));
}
else {
yield {val, depth}
}
}
}
let it = processData(testData, 0, true);
let res = it.next();
while(!res.done){
console.log(res.value)
res = it.next();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment