function flattenKeys(obj, delimiter) {
delimiter = delimiter || '.';
return recurse(obj, '', []);
function recurse(obj, path, result) {
if (typeof obj === "object") {
Object.keys(obj).forEach(function (key) {
recurse(obj[key], path + delimiter + key, result);
});
} else {
result.push(path.slice(delimiter.length));
}
return result;
}
}
used as
var obj = {
prop1 : {
x: 19,
y: 43
},
prop2 : {
another: {
here: 1
}
},
prop3: "hello"
};
flattenKeys(obj);
// -> ["prop1.x", "prop1.y", "prop2.another.here", "prop3"]
Alternative implementation without string operations:
function flattenKeys(obj, delimiter) {
delimiter = delimiter || '.';
return recurse(obj, [], []);
function recurse(obj, path, result) {
if (typeof obj === "object") {
Object.keys(obj).forEach(function (key) {
path.push(key);
recurse(obj[key], path, result);
path.pop();
});
} else {
result.push(path.join(delimiter));
}
return result;
}
}