【问题标题】:Javascript: How to filter an object array and sum resultJavascript:如何过滤对象数组并对结果求和
【发布时间】: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


【解决方案1】:
var example = [{a:1, b:2, c:3}, {a:4, b:5, c:6}, {a:7, b:8, c:9}]

var res = example.reduce((acc, curr) => {
    return acc = acc + curr.a + curr.b
}, 0)

您可以通过这种方式减少初始数组并获得所需的结果。 它以0为初始值,然后添加数组每个元素的ab属性

【讨论】:

  • 感谢您的回答!我忘了在问题中提及一些关键信息。我在我的问题中拥有的对象数组是我在现实中拥有的非常简化的版本。我的实际对象数组有大约 350 个属性。所以 return acc = curr.a + curr.b 需要一英里长。这就是为什么我真的需要某种过滤器,或者我可以创建一个新数组来忽略不需要的属性。
  • 有不同的答案here。希望对你有帮助
【解决方案2】:

如果你想要除“c”之外的所有“a”和“b”属性的总和,你可以这样做:

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

let totalSum = 0;
example.forEach(obj => {
    let objSum = obj.a + obj.b;
    totalSum += objSum;
})

【讨论】:

  • 感谢您的回答。在您回答后,我已对我的问题进行了编辑。我将拥有大约 350 个不同的属性,而不仅仅是 a、b 和 c。所以我正在寻找一种方法来找到它们的总和,而不必说明每个属性。
  • @Normajean 是的,我也添加了不同的答案。如果你需要的话,请看看。
【解决方案3】:

试试

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

let keys = Object.keys(example[0]).filter(k=> k!='c');
let sumObj = obj => keys.reduce((a,c)=> a + obj[c],0);

let totalSum = example.reduce((a,c)=> a + sumObj(c), 0);

console.log(totalSum);

【讨论】:

  • 感谢您的回答。在您回答后,我已对我的问题进行了编辑。我将拥有大约 350 个不同的属性,而不仅仅是 a、b 和 c。所以我正在寻找一种方法来找到它们的总和,而不必说明每个属性。
【解决方案4】:

如果您想添加对象的所有属性,除了一些之外,您可以通过循环遍历属性并检查它们是否是您要避免的属性并采取相应措施来过滤掉它们。

无论属性的数量及其名称如何,此代码都有效。如果您愿意,可以展开它以过滤掉更多属性。

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

const result = example.reduce((acc, cur) => {
  for (let el in cur) {
    acc += el !== "c" ? cur[el] : 0
  }
  return acc; 
}, 0)
console.log(result)

【讨论】:

    【解决方案5】:

    如果您只想排除“c”属性但包含数组对象的所有属性的值的总和,则可以这样做。

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

    【讨论】:

    • 这个也很好用。我仍然需要原始对象数组来进行其他计算。因此,我创建了 var example 的副本,并执行了您提供给副本的代码。
    • @Normajean 原始示例数组不受 forEach() 方法的影响。所以我认为你不需要创建一个不同的副本。干杯。
    • 非常感谢。我只是在学习 javascript,并且已经尝试找到解决方案大约 5 天。再次感谢!
    • 如果您觉得我的回答有用,请给我点赞。谢谢:)
    【解决方案6】:

    希望这会有所帮助。

    var example = [{a:1, b:2, c:3}, {a:4, b:5, c:6}, {a:7, b:8, c:9}];
    var sum = 0;
    for(var i = 0; i < example.length; i++){
        for(var j = 0; j < Object.keys(example[i]).length; j++){
            if(Object.keys(example[i])[j] != "c"){
            sum +=  parseInt(example[i][Object.keys(example[i])[j]]);
            }
        }
    }
    
    console.log(sum);
    

    【讨论】:

      【解决方案7】:

      好的,我发现你的现实对象是巨大的。你可以这样做:

      const result = example.map(item => {
          // first way (extract a, b)
          const {a, b} = item;
          // second way (omit c)
          const {c, ...rest} = item;
      })
      

      那么这里会发生什么。如果您更容易从初始对象中提取属性,那么您可以使用first way 并返回{a, b}。 如果最好省略属性,那么你去second way 并返回rest

      所以我采取第二种方式并继续代码

      const res = example.map(item => {
          const {c, ...rest} = item;
          return rest
      }).reduce((acc, curr) => {
          Object.values(curr).forEach(value => acc = acc + value);
          return acc
      }, 0);
      

      如果您选择第一种方式 - reducer 将相同,只有map return 会有所不同。

      【讨论】:

        【解决方案8】:

        您可以使用下面的函数并将要省略的键作为字符串数组传递给第二个参数。第一个参数将是列表本身。

        const sumWithout = (list, without) => {
          return list.reduce((acc, item) => {
            for (let [key, value] of Object.entries(item)) {
              if(!without.includes(key)){
                acc = Number(value) + acc;
              }
            }
        
            return acc;
          }, 0)
        }
        
        console.log(sumWithout(yourList, ['c', 'foo', '...' ]));
        

        【讨论】:

          【解决方案9】:

          您已经拥有添加所有属性的代码。
          Object.keys(y) 获取对象的所有属性,reducer 将它们与 y[z] 一起使用,假设 z='a' 这就像在做 y.a:解决方案是在reduce之前过滤不需要的属性

          变化就在这一行:

          var sumobjects = example.map(y => Object.keys(y).filter(k=>k!=='c').reduce((x,z) => x + y[z], 0));

          完整代码如下:

          var example = [{a:1, b:2, c:3}, {a:4, b:5, c:6}, {a:7, b:8, c:9}]
          var sumobjects = example.map(y => Object.keys(y).filter(k=>k!=='c').reduce((x,z) => x + y[z], 0));
          const reducer = (accumulator, currentValue) => accumulator + currentValue;
          const sumexample = sumobjects.reduce(reducer)
          console.log(sumexample);
          

          如果您想排除多个属性,您可以创建一个包含要避免的属性的数组:
          var exceptedProperties = ["c","d"];
          变化是

          var sumobjects = example.map(y => Object.keys(y).filter(k=>!exceptedProperties.some(p=>p===k))​​.reduce( (x,z) => x + y[z], 0));

          完整代码:

          var example = [{a:1, b:2, c:3, d:4}, {a:4, b:5, c:6, d:7}, {a:7, b:8, c:9, d:10}]
          var sumobjects = example.map(y => Object.keys(y).filter(k=>!exceptedProperties.some(p=>p===k)).reduce((x,z) => x + y[z], 0));
          const reducer = (accumulator, currentValue) => accumulator + currentValue;
          const sumexample = sumobjects.reduce(reducer)
          console.log(sumexample);
          

          【讨论】:

            猜你喜欢
            • 2016-10-24
            • 1970-01-01
            • 2022-07-13
            • 2021-04-23
            • 1970-01-01
            • 1970-01-01
            • 2020-07-21
            • 1970-01-01
            • 2012-11-15
            相关资源
            最近更新 更多