RoyBarOn
RoyBarOn

Reputation: 987

Issue with JavaScript recursive function

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",
 }]

Fiddle

Upvotes: 1

Views: 74

Answers (2)

Chandrakant Thakkar
Chandrakant Thakkar

Reputation: 978

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));

Upvotes: 0

Nenad Vracar
Nenad Vracar

Reputation: 122155

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))

Upvotes: 1

Related Questions