JavaScript递归函数的问题

时间:2017-12-05 11:23:59

标签: javascript recursion

我有一个嵌套对象的对象。我需要将所有子对象的所有键和值都放到一个数组中。

所以我试图用递归函数来做,但我想我做错了......

对象:

  function check(arr){
      var val = '';
      $.each(arr, function(k, v) {
          if (typeof v == "object" && v.length !== 0) {
              val = check(v); 
          }
      });

      return val;
 }

这是功能:

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

这是使用它的功能:

 [foo:{
  "gender": "male",
  "country": "us",
  "phone": "06 12 34 56 78",
  "company": "foo",
  "companyID": "12345678912345",
  "address": "adress principale",
 }]

预期产出:

For sql_id 'abcdefg', following were the execution time (in ms)
10
12
10
13
10
10
10
240
230
10
9
12
…
…

Fiddle

2 个答案:

答案 0 :(得分:1)

您可以使用Object.keys()reduce()方法创建递归函数。



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




答案 1 :(得分:0)

function merge_by_keys(){
    $arr = func_get_args();
    $num = func_num_args();

    $keys = array();
    $i = 0;
    for ($i=0; $i<$num; ++$i){
        $keys = array_merge($keys, array_keys($arr[$i]));
    }
    $keys = array_unique($keys);

    $merged = array();

    foreach ($keys as $key){
        $merged[$key] = array();
        for($i=0; $i<$num; ++$i){
            $merged[$key][] = isset($arr[$i][$key]) ? $arr[$i][$key] : null;
        }
    }
    return $merged;
}