I have an object with nested objects. I need to get all the keys and values from all the sub objects into one array.
So I'm trying to do it with a recursive function, but I guess I'm doing something wrong...
The object :
var jsonobj = {
"gender": "male",
"country": "us",
"phone": "06 12 34 56 78",
"enterprise": {
"parameters": {
"company": "foo",
"companyID": "12345678912345",
"address": "adress principale",
}
},
"contacts": [],
"requirements": []
}
Here is the function :
function check(arr){
var val = '';
$.each(arr, function(k, v) {
if (typeof v == "object" && v.length !== 0) {
val = check(v);
}
});
return val;
}
And this is the function using it :
function rec_res(obj_res) {
var foo=[];
$.each(jsonobj, function(k, v) {
if (typeof v == "object" && v.length !== 0) {
g = check(jsonobj); // calling the function
foo.push(g);
} else {
foo.push(v);
}
});
console.log(foo);
};
Expected output:
[foo:{
"gender": "male",
"country": "us",
"phone": "06 12 34 56 78",
"company": "foo",
"companyID": "12345678912345",
"address": "adress principale",
}]
jsonobjappears to be a global variable and you keep using that, when you probably meant$.each(obj, ...)