I am trying to convert json object into array of path string but not getting expected result.
Don't know might be other way to achieve the same but tried using for loop and lodash isObject and isEmpty for validate object like below.
Input Json:
const json = {
"info": {
"account": {}
},
"info2": {
"address": {
"mobile": {
"phone": null
}
},
"contact": {
"first": {}
}
}
}
javascript code:
var pathArray = this.convertJsonToArrayOfPathString(json);
console.log(pathArray);
convertJsonToArrayOfPathString(json, pathArray = [], path = '') {
const keys = Object.keys(json);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
path = path ? path + '.' + key : key;
if (_.isObject(json[key]) && !_.isEmpty(json[key])) {
this.convertJsonToArrayOfPathString(json[key], pathArray, path);
}
else {
pathArray.push(path)
path = ''
}
}
return pathArray;
}
expected output:
[
"info.account",
"info2.address.mobile.phone",
"info2.contact.first"
]
could you please any help. thanks.
foreachin your code example. Are you posting the correct version? There is no need forisObjectandisEmptycode if you use forEach.functionbefore the function.