How could i convert a json object from
{
'data': {
'x': {
'y': 1
}
}
}
to
{
'data': { 'x': { 'y': 1 } },
'data.x': { 'y': 1 },
'data.y': { 1 }
}
help is really needed :D
It is the bad way to handle json.
I suggest a function get
In lodash;
You can try
const ob = {
'data': {
'x': {
'y': 1
}
}
}
_.get(ob, 'data')
_.get(ob, 'data.x')
_.get(ob, 'data.x.y')
If you mean
{
'data': { 'x': { 'y': 1 } },
'data.x': { 'y': 1 },
'data.x.y': 1
}
You can do it with recursion:
const foo = {
'data': {
'x': {
'y': 1
}
}
};
const loop = (obj, path, result) => {
Object.entries(obj).forEach(([key, value]) => {
result[`${path ? path + '.' : ''}${key}`] = JSON.parse(JSON.stringify(value));
if(typeof value === 'object') {
loop(value, `${path ? path + '.' : ''}${key}`, result);
}
});
return result;
}
const result = loop(foo, '', {});
console.log(result);
{ 1 }
isn't