以递归方式查找数组对象中的项目数

时间:2017-06-08 13:22:23

标签: javascript recursion

在以下对象中获取titi数量的递归方法是什么:

{
    titi: "h0",
    history: [{
        titi: "h1",
        history: [{
            titi: "h11"
        }, {
            titi: "h12"
        }]
    }, {
        titi: "h12",
        history: [{
            titi: "h121"
        }, {
            titi: "h122"
        }]
    }]
}

预期结果是总数。在这个例子中:7。

4 个答案:

答案 0 :(得分:1)



var data = {
  titi: "h0",
  history: [{
    titi: "h1",
    history: [{
      titi: "h11"
    }, {
      titi: "h12"
    }]
  }, {
    titi: "h12",
    history: [{
      titi: "h121"
    }, {
      titi: "h122"
    }]
  }]
}

var numberOfTiti = 0;
function process (obj) {
  for (var index in obj) {
    if (index === 'titi') {
      numberOfTiti++;
    }
    if (typeof obj[index] === 'object') {
      process(obj[index]);
    }
  }
}

process(data);
console.log(numberOfTiti);




答案 1 :(得分:1)

var json = {  titi:"h0", history : [{ titi :"h1", history : [{ titi :"h11"}, { titi : "h12"}] }, { titi : "h12", history : [{ titi :"h121"}, { titi : "h122"}]}]}

var count = 0;

function getCount(haystack, needle) {
    for (var k in haystack) {
        if (haystack.hasOwnProperty(k)) {
          if ( k == needle ) {count = count + 1};
          if (typeof haystack[k] === 'object') getCount(haystack[k], needle);
        }
    }
}

getCount(json, 'titi');
console.log('count: ',count)

答案 2 :(得分:1)

使用JSON.stringify

function countTiti(obj) {
  let count = 0;
  JSON.stringify(obj, (k, v) => { if (k === 'titi') count++; return v; });
  return count;
}

答案 3 :(得分:-1)

这是一个有趣,简单,无限递归的方法:



let obj = {
    titi: "h0",
    history: [{
        titi: "h1",
        history: [{
            titi: "h11"
        }, {
            titi: "h12"
        }]
    }, {
        titi: "h12",
        history: [{
            titi: "h121"
        }, {
            titi: "h122"
        }]
    }]
}

let count = JSON.stringify(obj).match(/"titi":/g).length

console.log(count) // 7