使用对象内的对象过滤数组

Kam*_*ski 8 javascript arrays

我有一个使用嵌套对象过滤数组的问题.

[{
    "firstName": "Kevin",
    "lastName": "Smith",
    "expenses": {
      "drink1": 25,
      "drink2": 20
    }
  },
  {
    "firstName": "John",
    "lastName": "Rambo",
    "expenses": {
      "coffe": 10,
      "cake": 20
    }
  }
]
Run Code Online (Sandbox Code Playgroud)

我想得到所有费用总和> 35的物品.怎么进去expenses?或者过滤器在这里可能不合适.

sja*_*han 10

filter这样,用条件reduce来计算费用!挺直的:)

const input = [{
    "firstName": "Kevin",
    "lastName": "Smith",
    "expenses": {
      "drink1": 26,
      "drink2": 20
    }
  },
  {
    "firstName": "John",
    "lastName": "Rambo",
    "expenses": {
      "coffe": 10,
      "cake": 20
    }
  }
];

const output = input.filter(user => Object.values(user.expenses).reduce((acc, expense) => acc + expense) > 45);
console.log(output);
Run Code Online (Sandbox Code Playgroud)


Vel*_*sky -3

一个可能的解决方案可能是:

arr.filter(function(v){ for(expense in v.expenses){ if(v.expenses[expense] > 10){ return true; }else{ return false; } } })

  • 因此,如果他们询问如何对所有属性值求和,您将展示如何访问单个属性,因为实际回答这个问题会太多?奥奥 (3认同)