使用此数据,如何找到Customer对象和所有子元素对象的键计数?
const Customer = {
"Profile": {
"A1": {
"A2": "",
"A3": "E",
"A4": "",
"A5": {
"Cus": "",
"Bil": ""
},
"Services": [{
"vA": {
"Status": 2,
"Switch-CLLi": "",
"PLIST": [{
"Status": "",
"Price": 0
}, {
"Status": "",
"Price": 40
}]
}
}]
},
"B1": {
"B2": 953108717,
"B3": "04"
}
}}
答案 0 :(得分:0)
您可以为此进行用户递归。
const countKeys = (obj, result) => {
const keys = Object.keys(obj);
result.sum+= keys.length;
result.keys = [...result.keys, ...keys];
keys.forEach(key => {
if(typeof(obj[key]) === 'object')
result= countKeys(obj[key],result);
})
return result;
};
在您的方法中调用此方法
const totalKeys = countKeys(yourObject, { sum: 0, keys: []});
答案 1 :(得分:0)
尽量不要重新发明轮子,而要找到一个很好的数据处理库并进行学习。我们几乎所有内容都使用object-scan。一旦将头缠住它,它就会非常强大。这是解决问题的方法
const objectScan = require('object-scan');
const count = (data) => objectScan(['**'], {
filterFn: ({ property, context }) => {
if (typeof property === 'string') {
context[property] = (context[property] || 0) + 1;
}
}
})(data, {});
const Customer = {"Profile":{"A1":{"A2":"","A3":"E","A4":"","A5":{"Cus":"","Bil":""},"Services":[{"vA":{"Status":2,"Switch-CLLi":"","PLIST":[{"Status":"","Price":0},{"Status":"","Price":40}]}}]},"B1":{"B2":953108717,"B3":"04"}}};
console.log(JSON.stringify(count(Customer)));
// => {"B3":1,"B2":1,"B1":1,"Price":2,"Status":3,"PLIST":1,"Switch-CLLi":1,"vA":1,"Services":1,"Bil":1,"Cus":1,"A5":1,"A4":1,"A3":1,"A2":1,"A1":1,"Profile":1}