Reputation: 544
I'm wondering if its possible to retrieve all paths a javascript object contains
Example:
obj = {
prop1 : {
x: 19
y: 43
}
prop2 : {
another: {
here: 1
}
}
prop3: "hello"
}
Where the result would be an array with following elements:
Result: ["prop1.x", "prop1.y", "prop2.another.here", "prop3"]
Is this possible?
Thanks!
Upvotes: 1
Views: 111
Reputation: 6908
Wrote this while Tomalak was putting together here. Recursion's the obvious approach for doing this.
var inputObject = {
prop1: {
x: 19,
y: 43
},
prop2: {
another: {
here: 1
}
},
prop3: "hello"
};
function getProps(obj) {
var props = [];
var findPropsRecursive = function (robj, str) {
robj = robj || {};
var keys = Object.keys(robj);
if (keys.length > 0 && (robj instanceof Object)) {
return keys.map(function (key) {
return findPropsRecursive(robj[key], str + (str ? '.' : '') + key);
});
} else {
props.push(str);
return '';
}
};
findPropsRecursive(obj, '');
return props;
}
console.log(getProps(inputObject));
on jsfiddle: http://jsfiddle.net/jkoudys/w49rcp40/
Upvotes: 2
Reputation: 338406
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;
}
}
Upvotes: 3