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

时间:2018-11-07 18:42:51

标签: javascript arrays

我在过滤带有嵌套对象的数组时遇到问题。

[{
    "firstName": "Kevin",
    "lastName": "Smith",
    "expenses": {
      "drink1": 25,
      "drink2": 20
    }
  },
  {
    "firstName": "John",
    "lastName": "Rambo",
    "expenses": {
      "coffe": 10,
      "cake": 20
    }
  }
]

我想获取所有支出之和> 35的对象。如何进入expenses?也许在这里过滤不是正确的方法。

5 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

您可以尝试这样的事情

var data = [{
    "firstName": "Kevin",
    "lastName": "Smith",
    "expenses": {
      "drink1": 25,
      "drink2": 20
    }
  },
  {
    "firstName": "John",
    "lastName": "Rambo",
    "expenses": {
      "coffe": 10,
      "cake": 20
    }
  }
]

var filtered = data.filter(c => Object.keys(c.expenses)
                                .reduce(function(p, e) {
                                     return p + c.expenses[e]
                                       }, 0) >= 35
                           );

console.log(filtered);

答案 2 :(得分:0)

您可以使用表达式i访问数组arr内索引arr[i]处的对象 您需要做的是遍历数组。在循环内,您可以访问我提到的带有表达式的每个对象:arr[i],然后在此对象上,可以按照arr[i].expenses的方式访问费用,此后,如果我理解正确,您可以将{{1 }}对象,然后选择满足您条件的对象。 请,请参见下面的代码:

arr[i].expenses

您已经将结果放入数组var expensesAbove35Arr = []; var yourArray = [ { "firstName": "Kevin", "lastName": "Smith", "expenses": { "drink1": 26, "drink2": 20 } }, { "firstName": "John", "lastName": "Rambo", "expenses": { "coffe": 10, "cake": 20 } } ]; for(var i=0; i<yourArray.length; i++){ if(yourArray[i].expenses.coffe + yourArray[i].expenses.cake > 35 ){ expensesAbove35Arr.push(yourArray[i]); } }

答案 3 :(得分:0)

我假设您需要按原样保留一系列用户,但要过滤掉费用。

(我认为评论中指出的错误,请保留此答案,以防万一有人看到它的任何价值)

这可能是最佳化或简化的,但是在这里:

arr.reduce((acc, user) => [...acc,
  Object.keys(user).reduce((userResult, key) => {
    if (key === 'expenses') {
      return {
         ...userResult,
        expenses: Object.entries(elem.expenses)
          .filter(([product, value]) => value > 35)
          // now "reversing" the object.entries
          .reduce((acc, [product, value]) => ({ [product]: value }), {})
      }
    }
    return {
      ...userResult,
      [key]: elem[key]
    }
  }, user) // starts with the user
], []) //starts with empty array

答案 4 :(得分:-2)

可能的解决方案可能是:

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