I need get path with object jeys of JS. Function must pass thrught all object, even if he will deep.
Input data
{
tree1: {
node1: 'valOfnode1',
node2: 'valOfnode2',
node3: 'valOfnode3',
node4: {
node5: 'valOfnode5',
node6: 'valOfnode6',
node7: {
node8: 'valOfnode8',
node9: 'surprize!',
},
}
}
};
Output data
[
['tree1.node1': 'valOfnode1'],
['tree1.node2': 'valOfnode2'],
['tree1.node3': 'valOfnode3'],
['tree1.node4.node5': 'valOfnode5'],
['tree1.node4.node6': 'valOfNode6'],
['tree1.node4.node7.node8': 'valOfNode8'],
['tree1.node4.node7.node9': 'surprize!'],
]
I tryed made a function, but in result i get all paths.
It is a my function. This function need for get depth of every path.
const sortObject = (obj) => {
const arr = [];
const entries = Object.entries(obj);
let headKey;
const iter = (data) => {
const keys = Object.keys(data);
keys.forEach((key) => {
if (typeof data[keys] !== 'object') {
arr.push(`${headKey}.${keys}`);
console.log(arr);
} if (typeof data[keys] === 'object') {
return iter(data[keys]);
}
});
}
return entries.forEach(([key, value]) => {
headKey = key;
if (typeof value === 'object') {
return iter(value);
}
})
console.log(arr);
}
3
Answers
Use an array variable
stack
to store objects and their prefixes. do awhile
loop as long as there areobjects
in thestack
. each iterationpop
an object and its prefix from thestack
, then loop over the properties of the object and check if the value is another object, if so push it onto the stack and update theprefix
. Otherwise add the key-value pair with the concatenatedprefix
flattened key-value pairs:Recursively walk by object keys and collect the paths: