我有一个带有多个嵌套对象的javascript对象,如下所示:
var stats = {
bookServed: {
redis: 90,
s3: 90,
signedUrl: 70
},
errors: {
redis: {
bookService: 70,
mapi: 50,
capi: 30
},
AWS: {
signedUrl: 70,
downloadBook: 50,
searchBook: 10
},
decryption: 60
}
};
例如,迭代所有属性并将每个值设置为0
的最简洁方法是什么。我写了这样的东西
for (var property in stats) {
if (stats.hasOwnProperty(property)) {
if (typeof property === "object") {
for (var sub_property in property)
if (property.hasOwnProperty(sub_property)) {
sub_property = 0
}
} else {
property = 0;
}
}
}
我愿意使用像underscore.js这样的库来正确完成任务。
答案 0 :(得分:4)
相对简单的递归问题,我会使用一个在找到子对象时调用自身的函数。我也会避免使用for循环,而是在对象的键上使用forEach(它更快,并且不需要hasOwnProperty检查。)
function resetValuesToZero (obj) {
Object.keys(obj).forEach(function (key) {
if (typeof obj[key] === 'object') {
return resetValuesToZero(obj[key]);
}
obj[key] = 0;
});
}
var stats = {
bookServed: {
redis: 90,
s3: 90,
signedUrl: 70
},
errors: {
redis: {
bookService: 70,
mapi: 50,
capi: 30
},
AWS: {
signedUrl: 70,
downloadBook: 50,
searchBook: 10
},
decryption: 60
}
};
console.log(stats.errors.AWS.signedUrl); // 70
resetValuesToZero(stats);
console.log(stats.errors.AWS.signedUrl); // 0
答案 1 :(得分:0)
以下解决方案使用object-scan,它使用迭代实现遍历输入。还要注意,这将遍历任何类似于已接受答案的数组结构。
const objectScan = require('object-scan');
const rewriter = objectScan(['**'], {
rtn: 'count',
filterFn: ({ value, parent, property }) => {
if (typeof value === 'number') {
parent[property] = 0;
return true;
}
return false;
}
});
const stats = {"bookServed":{"redis":90,"s3":90,"signedUrl":70},"errors":{"redis":{"bookService":70,"mapi":50,"capi":30},"AWS":{"signedUrl":70,"downloadBook":50,"searchBook":10},"decryption":60}};
console.log(rewriter(stats)); // returns count of replaces
// => 10
console.log(stats);
/* =>
{ bookServed: { redis: 0, s3: 0, signedUrl: 0 },
errors:
{ redis: { bookService: 0, mapi: 0, capi: 0 },
AWS: { signedUrl: 0, downloadBook: 0, searchBook: 0 },
decryption: 0 } }
*/
答案 2 :(得分:0)
function checkNPE(obj) {
for(const name in obj){console.log('name: ' + JSON.stringify(name, null, 4));
if (typeof obj[name] === 'object') {console.log('object name: ' + JSON.stringify(name, null, 4));
checkNPE(obj[name]);
} // if (typeof obj[name] === 'object') {
} // for(const name in obj){
}; // function checkNPE (obj) {
var stats = {
bookServed: {
redis: 90,
s3: 90,
signedUrl: 70
},
errors: {
redis: {
bookService: 70,
mapi: 50,
capi: 30
},
AWS: {
signedUrl: 70,
downloadBook: 'a',
searchBook: 10
},
decryption: 60
}
};
checkNPE(stats);