I have a JSON data which can be an object/array of recursively nested object or array. The value of an array can not be null, but an value in a object can be null. I would like to return all combination of these keys and values through depth first search.
For example:
var data = {
"title": {
"original": "Hitchhiker",
"more": ["HGTTG"],
"link": null
},
"date": ["20150101", "20160101"]
}
The data's length and depth is arbitrary, and the combination result I want is something like this:
["title-original-Hitchhiker", "title-more-HTTG", "title-link", "date-20150101", "date-20160101"]
What I came up with is recursive:
function nestedObjectToArray(obj) {
if (typeof(obj) != "object"){
return [obj];
}
var result = [];
if (obj.constructor == Array){
for (var i = 0; i <obj.length; i++){
if (obj[i]){
var temp = nestedObjectToArray(obj[i]);
for (var j = 0; j < temp.length; j++){
result.push(temp[j]);
}
}
}
} else {
for (var i in obj){
if (obj.hasOwnProperty(i)) {
if (obj[i] == null){
result.push(i);
} else {
var temp = nestedObjectToArray(obj[i]);
for (var j = 0; j < temp.length; j++){
result.push(i+"-"+temp[j]);
}
}
}
}
}
return result;
}
Would you have a better/more elegant solution then this chunk of conditions, loops and recursion? I can use any lib if it's more convenient.