【发布时间】:2019-12-21 15:19:51
【问题描述】:
我有一个对象数组:
var example = [{a:1, b:2, c:3}, {a:4, b:5, c:6}, {a:7, b:8, c:9}]
我正在尝试添加与c 不对应的所有值。
我已经设法用 console.log(test.filter(x => xc > 3));
我也尝试过数据查询并将 .ne("c") 链接到它,但这不起作用。
我已经设法找到一个对象数组的总和,但它并没有省略与“c”对应的元素。代码是:
var example = [{a:1, b:2, c:3}, {a:4, b:5, c:6}, {a:7, b:8, c:9}]
var sumobjects
sumobjects = example.map(y => Object.keys(y).reduce((x,z) => x + y[z], 0));
const reducer = (accumulator, currentValue) => accumulator + currentValue;
const sumexample = sumobjects.reduce(reducer)
console.log(sumexample);
我当前的代码如下所示:
var example = [{a:1, b:2, c:3}, {a:4, b:5, c:6}, {a:7, b:8, c:9}]
function filtration (arr) {
var filteredsum = 0
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr[i].length; j++) {
for(let k = 0; k < arr[i][j].length && arr[i][j] !== "c"; k++)
filteredsum += arr[i][j]
}
}
return(filteredsum);
}
console.log(filtration(example));
答案应该是一个单一的数字,即27。
我目前的代码是输出0,所以我认为不是从总和中省略属性“c”,而是找到c,然后从对象数组中省略整个对象。
编辑:上面的对象数组是我实际使用的对象数组的简化版本。实际的对象数组不限于属性 a、b 和 c。它有大约 350 种不同的属性。因此,通过实际声明 a、b 和 c 来添加 a、b 和 c 的代码对我来说不是一个好的选择。
【问题讨论】:
-
您的对象只有 a、b、c 属性还是可以有其他属性?
-
它将有大约 350 个属性
标签: javascript arrays object filter sum