nde*_*n11 3 javascript recursion
我试图得到嵌套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);
Run Code Online (Sandbox Code Playgroud)
如果属性为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>');Run Code Online (Sandbox Code Playgroud)
额外奖励:内置计数功能样式的版本
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>');Run Code Online (Sandbox Code Playgroud)
这是一种简短而笨拙的方法:
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
Run Code Online (Sandbox Code Playgroud)
分解
这另一个解决方案将创建一个数组,告诉您每个级别中有多少项目
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]
Run Code Online (Sandbox Code Playgroud)
说明:1级:2项,2级:2项,3级:1项