问题
Having the object :
Nested1: {
"nested21": {
"nested31": {
value: "im sooo nested"
} ,
"nested32": {
value: "im sooo nested"
}
},
"nested22": {
"nested31": {
value: "im sooo nested"
} ,
"nested32": {
value: "im sooo nested"
}
}
}
Where there can be an undefined number of nested objects, i'd like to get something like:
Nested1.nested21.nested31 - im sooo nested Nested1.nested21.nested32 - im sooo nested
And so on
I'm thinking of a recursive function but how to keep in memory the chained keys ?
回答1:
Got it
var obj, traverse;
obj = {
a: {
b: 1,
c: 2
},
d: {
e: 3,
f: 4
}
};
traverse = function(node, path) {
var pairs;
if (!(pairs = _(node).pairs()).length) {
return [
{
keys: path,
value: node
}
];
} else {
return [].concat.apply([], _(pairs).map(function(kv) {
return traverse(kv[1], path.concat(kv[0]));
}));
}
};
console.log(traverse(obj, []));
来源:https://stackoverflow.com/questions/17231118/javascript-iterate-over-nested-objects-getting-values-and-chained-keys