I hope that someone can help me with the following.
I want to traverse through a deeply nested JSON-object and generate a dictionary with the traversed path and corresponding value(s).
My object looks like this:
{
title: 'Mr.',
user: {
address: {
city: 'Amsterdam'
},
name: {
first: 'MyFirstName',
last: 'MyLastName'
}
}
}
The result I'm after looks like this:
{
'title': 'Mr.',
'user.address.city': 'Amsterdam',
'user.name.first': 'MyFirstName',
'user.name.last': 'MyLastName'
}
I used Object.Entries
method to traverse through key/value pairs and used recursion to generate an Array of keys, but it doesn't handle siblings on deeper levels very well...
I already looked at "Traverse all the Nodes of a JSON Object Tree with JavaScript ", but it didn't solve my problem since I want to generate a dictionary where the traversed path is the key and where the deepest node is the value.
I want to stress that I'm looking for a native JavaScript solution without any framework or library.
The current result is:
[
"user.address.city",
"user.name.first,name.last",
"user.occupation.job.description.name,description.title"
]
My code:
const obj = {
title: 'Mr.',
user: {
address: {
city: 'Amsterdam'
},
name: {
first: 'MyFirstName',
last: 'MyLastName'
}
}
};
const isObject = (obj) => Object.prototype.toString.call(obj).indexOf("Object") > -1;
const generateBindingKeys = (key, obj) => {
//return an array of keybindings, because there can be more siblings in one node
return Object.keys(obj).map(k => isObject(obj[k]) ? `${key}.${generateBindingKeys(k, obj[k])}` : `${key}.${k}`);
};
// traverse all entries in the new state
Object.entries(obj).forEach(([key, val]) => {
// generate the binding
// if there are children we need to recursively traverse through the path and return the keys
const bindings = isObject(val) ? generateBindingKeys(key, val) : key;
console.log(bindings);
});