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",
}]
asked Dec 5, 2017 at 11:23
RoyBarOn
1,0093 gold badges30 silver badges77 bronze badges
2 Answers 2
You can create recursive function with Object.keys() and reduce() methods.
var jsonobj = {
"gender": "male",
"country": "us",
"phone": "06 12 34 56 78",
"enterprise": {
"parameters": {
"company": "foo",
"companyID": "12345678912345",
"address": "adress principale",
}
},
"contacts": [],
"requirements": []
}
function rec_res(obj) {
return Object.keys(obj).reduce((r, e) => {
if(typeof obj[e] == 'object') Object.assign(r, rec_res(obj[e]))
else r[e] = obj[e];
return r;
}, {})
}
console.log(rec_res(jsonobj))
answered Dec 5, 2017 at 11:35
Nenad Vracar
122k16 gold badges160 silver badges184 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
RoyBarOn
Sorry - i can't implement it , need it to be native.... any idea why mine isn't working?
Nenad Vracar
What do you mean by native?
var jsonobj = {
"gender": "male",
"country": "us",
"phone": "06 12 34 56 78",
"enterprise": {
"parameters": {
"company": "foo",
"companyID": "12345678912345",
"address": "adress principale",
}
},
"contacts": [],
"requirements": []
}
var result=[];
function rec_res(obj_res) {
var foo=[];
$.each(Object.keys(obj_res), function(k, v) {
if (typeof obj_res[v] == "object") {
var data = rec_res(obj_res[v]);
if(data!=undefined && data.length!=0){
data.map(function(d){
result.push(d);
});
}
} else {
result.push({[v]:obj_res[v]});
foo.push({[v]:obj_res[v]});
}
return foo;
});
//console.log(foo);
};
rec_res(jsonobj);
alert(JSON.stringify(result));
answered Dec 5, 2017 at 11:55
Chandrakant Thakkar
9789 silver badges23 bronze badges
Comments
lang-js
jsonobjappears to be a global variable and you keep using that, when you probably meant$.each(obj, ...)