如何查找对象中存在的键总数以及分配给javascript中变量的内部嵌套对象



使用这些数据,我如何找到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"
}
}} 

您可以为此使用递归。

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: []});

尽量不要重新发明轮子,找到一个好的数据处理库并学习它。我们几乎对所有东西都使用对象扫描。一旦你把你的头缠在它周围,它就非常强大。以下是你如何解决你的问题

// 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(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 }
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan@13.8.0"></script>

免责声明:我是物体扫描的作者

最新更新