簡體   English   中英

計算對象和所有子項中的字符串總數

[英]Count the total number of strings in object and all children

我有一個對象,可能包含對象(反過來可能包含或不包含對象,等等到無窮大),並帶有字符串,如下所示:

var obj = {
    "foo": "hello",
    "bar": "hi",
    "test": {
        "foo": "foo"
        "bar": {
            "test": "hi",
            "hello": "howdy"
        }
    }
}

我想要做的是計算整個obj對象及其子對象中的字符串數。 在這個例子中,正確的答案是5。

關於計算此站點上的對象中的鍵的眾多主題都建議使用.hasOwnProperty的循環或新的Object.keys(obj)方式,但這些都不是遞歸的,並且它們都計算子對象本身。

完成此任務的最佳方法是什么?

您可以創建遞歸函數,循環嵌套對象並返回計數。

 var obj = { "foo": "hello", "bar": "hi", "test": { "foo": "foo", "bar": { "test": "hi", "hello": "howdy" } } } function countS(data) { var c = 0; for (var i in data) { if (typeof data[i] == 'object') c += countS(data[i]); if (typeof data[i] == 'string') c += 1 } return c; } console.log(countS(obj)) 

這是功能編程風格的ES6功能:

 function countPrimitives(obj) { return +(Object(obj) !== obj) || Object.keys(obj).reduce( (cnt, key) => cnt + countPrimitives(obj[key]), 0 ); } var obj = { "foo": "hello", "bar": "hi", "test": { "foo": "foo", "bar": { "test": "hi", "hello": "howdy" } } }; console.log(countPrimitives(obj)); 

實際上,這也將計算其他原始值,包括數字和布爾值,......:任何不是嵌套對象的東西。

您可以使用Array#reduce迭代鍵並檢查Object。

 function getCount(object) { return Object.keys(object).reduce(function (r, k) { return r + (object[k] && typeof object[k] === 'object' ? getCount(object[k]) : 1); }, 0); } var obj = { foo: "hello", bar: "hi", test: { foo: "foo", bar: { test: "hi", hello: "howdy" } } }, count = getCount(obj); console.log(count); 

使用您提到的任何一種方法循環。

像這樣的東西:

 var obj = { "foo": "hello", "bar": "hi", "test": { "foo": "foo", "bar": { "test": "hi", "hello": "howdy" } } } function count_strings(obj) { var count = 0; var keys = Object.keys(obj); for (var i=0, l=keys.length; i<l; i++) { if (typeof obj[keys[i]] === 'object') { count += count_strings(obj[keys[i]]); } else if (typeof obj[keys[i]] === 'string') { count++; } } return count; } document.querySelector('.output').innerHTML = count_strings(obj); 
 <div class="output"></div> 

這也是我的50分。

function checkString(str){
  var count = 0;
  if(typeof str  === 'string'){
    return 1;
  }
  Object.keys(str).forEach(function(v){
    console.log(str[v]);
    if(typeof str[v] === 'object') count = count + checkString(str[v])
    else count ++;
  })
  return count;
}

var obj = {
    "foo": "hello",
    "bar": "hi",
    "test": {
        "foo": "foo"
        "bar": {
            "test": "hi",
            "hello": "howdy"
        }
    }
};
console.log(checkString(obj));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM