javascript - Count the total number of strings in object and all children - Stack Overflow

I have an object that may contain objects (which in turn may or may not contain objects, etc to infinit

I have an object that may contain objects (which in turn may or may not contain objects, etc to infinity), with strings thrown in, like so:

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

What I want to do is count the number of strings in the entire obj object and its children. In this example, the correct answer would be 5.

The numerous topics about counting keys in objects on this site all suggest either a loop with .hasOwnProperty or the new Object.keys(obj) way of things, but neither of these are recursive, and both of them count the child objects themselves.

What is the best way to acplish this?

I have an object that may contain objects (which in turn may or may not contain objects, etc to infinity), with strings thrown in, like so:

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

What I want to do is count the number of strings in the entire obj object and its children. In this example, the correct answer would be 5.

The numerous topics about counting keys in objects on this site all suggest either a loop with .hasOwnProperty or the new Object.keys(obj) way of things, but neither of these are recursive, and both of them count the child objects themselves.

What is the best way to acplish this?

Share Improve this question asked Jan 10, 2017 at 18:48 Emphram StavangerEmphram Stavanger 4,2249 gold badges38 silver badges66 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 6

You can create recursive function that will loop nested objects and return count.

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

You could use Array#reduce with iterating over the keys and checking for 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);

Here is functional programming style ES6 function for it:

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

In fact this will also count other primitive values, including numbers and booleans, ...: anything that is not a nested object.

Loop with either of the methods you mentioned.

Something like this:

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>

Here is 50 cent of mine too.

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744322031a4568466.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信