计算嵌套对象中的键

时间:2015-09-17 18:09:01

标签: javascript

我试图获得嵌套JS对象中的键的计数。我能够达到第一级,但我有点困惑于如何深入挖掘嵌套对象并返回计数。

var properties = {
prop1: '',
prop2: '',
prop3: '',
prop4: {
    subProp1: '',
    subProp2: '',
    subProp3: {
        subSubprop1: ''
        }
    }
}

var getCount = function (data) {
var count = 0;
for (var k in data) {
    if (properties.hasOwnProperty(k)) {
        ++count;
    }
}
console.log( "this is the count for level 0: " + count //returns 4);
console.log( "this is the count for level 1: " + count //should return 3);
console.log( "this is the count for level 2: " + count //should return 1);
return count;
}
getCount(properties);

3 个答案:

答案 0 :(得分:7)

如果属性为object

,您可以进行递归

 var properties = {
        prop1: '',
        prop2: '',
        prop3: '',
        prop4: {
            subProp1: '',
            subProp2: '',
            subProp3: {
                subSubprop1: ''
            }
        }
    },
    count = [];

// i suggest to use named function for recursion, because the name is used
// inside the function. otherwise it is not safe, if the name does not
// match the given name at assignment
function getCount(data, level) {
    level = level || 0;
    count[level] = count[level] || 0;
    for (var k in data) {
        data.hasOwnProperty(k) && count[level]++;
        typeof data[k] === 'object' && getCount(data[k], level + 1);
    }
}

getCount(properties);
document.write('<pre>' + JSON.stringify(count, 0, 4) + '</pre>');

奖励:具有功能样式内置计数的版本

var properties = {
        prop1: '',
        prop2: '',
        prop3: '',
        prop4: {
            subProp1: '',
            subProp2: '',
            subProp3: {
                subSubprop1: ''
            }
        }
    };

function f(o, l, r) {
    l = l || 0;            
    return Object.keys(o).reduce(function (r, k) {
        r[l] = (r[l] || 0) + 1;
        typeof o[k] === 'object' && f(o[k], l + 1, r);
        return r;
    }, r || []);
}

document.write('<pre>' + JSON.stringify(f(properties), 0, 4) + '</pre>');

答案 1 :(得分:3)

这是一种简短易懂的方法:

var obj={a:0,b:1,c:{a:1,otherkeyb:'2:"":2\\',otherkey:{d:1,e:2}}}
JSON.stringify(obj).match(/[^\\]":/g).length // return 8

细分

这另一个解决方案将创建一个数组,告诉你每个级别有多少项

var count_in_level = []
var obj = {
    a: 0,
    b: {
        ba: 1,
        c: {
            ca: 1,
            cb: 2
        }
    }
}
function count(obj, level) {
    var c = 0
    if (typeof level == 'undefined') level = 1
    if (!count_in_level[level]) count_in_level[level] = 0
    if (typeof obj == 'object') {
        for (var i in obj) {
            if (typeof obj[i] == 'object') count(obj[i], level + 1)
            c++;
        }
        count_in_level[level] += c
    }
}
count(obj);
console.log(count_in_level)  // [1: 2, 2: 2, 3: 1]

说明:1级:2项,2级:2项,3级:1项

答案 2 :(得分:2)

如何使用Object.keys(如果可用[例如在IE&lt; 9中不支持])并将计数存储在对象中,其中键是关卡,值是计数?

var properties = {
    prop1: '',
    prop2: '',
    prop3: '',
    prop4: {
        subProp1: '',
        subProp2: '',
        subProp3: {
            subSubprop1: ''
        }
    }
};

function countKeysPerLevel(store, level, obj) {
    var keys = Object.keys(obj);
    var count = keys.length;

    store[level] = (store[level] || 0) + count;

    for (var i = 0; i < count; i++) {
        var childObj = obj[keys[i]];
        if (typeof childObj === 'object') {
            countKeysPerLevel(store, level + 1, childObj);
        }
    }
}

var result = {};
countKeysPerLevel(result, 0, properties);