Javascript:如何过滤对象数组和求和结果 [英] Javascript: How to filter an object array and sum result

查看:133
本文介绍了Javascript:如何过滤对象数组和求和结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象数组:

var example = [{a:1, b:2, c:3}, {a:4, b:5, c:6}, {a:7, b:8, c:9}]

我正在尝试添加所有与 c 不对应的值。

I am trying to add all values that don't correspond with c.


  • 我已经成功地用console.log(test.filter(x => xc> 3));过滤掉了我想要的那一行;

  • I've managed to filter out a row, which wasn't what I was after, with console.log(test.filter(x => x.c > 3));

我也尝试了数据查询并将.ne( c)链接到它,但这没有用。

I've also tried a data query and chaining .ne("c") to it, but this didn't work.

我设法找到了对象数组的总和,但是它没有忽略与 c相对应的元素。相应的代码是:

I have managed to find the sum of an object array, but it doesn't omit the elements corresponding with "c". The code for that is:

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

The answer should be one single number, being 27.

我当前拥有的代码输出 0 ,因此我认为与其忽略属性 c,从总和中找到 c ,然后从对象数组中省略整个对象。

The code I currently have is outputting 0, so I figure that instead of omitting the property "c" from the sum, it's finding c and then omitting the entire object from the object array.

编辑:上面的对象数组是我实际使用的对象数组的简化版本。实际的对象数组不限于属性a,b和c。它具有大约350种不同的属性。因此,通过实际声明a,b和c来添加a,b和c的代码对我来说不是一个好选择。

The object array above is a simplified version of the object array I'm actually working with. The actual object array is not limited to the properties a, b and c. It has about 350 different properties. So code that adds a and b and c by actually stating a, b and c isn't going to be a good option for me.

推荐答案

如果只想排除 c属性,但要包括数组对象所有属性的值之和,就可以这样做。

You can do like this if you just want to exclude "c" property but include sum of values of all properties of objects of the array.

var example = [{a:1, b:2, c:3}, {a:4, b:5, c:6}, {a:7, b:8, c:9}];

let sum = 0; 
example.forEach(obj => {
    for (let property in obj) {
        if(property !== "c")
        sum += obj[property];
    }
})

这篇关于Javascript:如何过滤对象数组和求和结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆