【发布时间】:2019-02-03 08:11:56
【问题描述】:
如何在可迭代对象(如数组)中总结特定键的值,而特定键可以嵌套在对象键中。 例子: 如何求键名为val的键值的总和?
var list = {
val: 5,
child1: {
val : 10,
someotherKey: 'somevalue'
},
child2: {
val : 20,
someotherKey2: 'someothervalue
},
child3: {
someval: {
val: 15,
somekey3: 'somevalue3'
}
}
}
我尝试使用 for in 循环 for( 列表中的键) {
for(key in list) {
if(key === 'val') {
console.log(key);
}
if(list[key]['val']) {
console.log(key);
}
}
但无法找到解决方案。
【问题讨论】:
-
val键可以嵌套多深?只是一个级别,还是一个任意数字? -
附注您的数据中没有可迭代数组
-
使用
Array.prototype.reduce(),reduce()方法对累加器和数组的每个值应用函数以将其减少为单个值。
标签: javascript arraylist javascript-objects