通过多个键过滤对象数组

时间:2019-01-19 19:55:39

标签: javascript arrays

我有一个对象数组,这些对象具有使用javascript的重复键:

var transactions = [
          {
            id: 3,
            sourceAccount: 'A',
            targetAccount: 'B',
            amount: 100,
            category: 'eating_out',
            time: '2018-03-02T10:34:30.000Z'
          },
          {
            id: 1,
            sourceAccount: 'A',
            targetAccount: 'B',
            amount: 100,
            category: 'eating_out',
            time: '2018-03-02T10:33:00.000Z'
          },
          {
            id: 6,
            sourceAccount: 'A',
            targetAccount: 'C',
            amount: 250,
            category: 'other',
            time: '2018-03-02T10:33:05.000Z'
          },
          {
            id: 4,
            sourceAccount: 'A',
            targetAccount: 'B',
            amount: 100,
            category: 'eating_out',
            time: '2018-03-02T10:36:00.000Z'
          },
          {
            id: 2,
            sourceAccount: 'A',
            targetAccount: 'B',
            amount: 100,
            category: 'eating_out',
            time: '2018-03-02T10:33:50.000Z'
          },
          {
            id: 5,
            sourceAccount: 'A',
            targetAccount: 'C',
            amount: 250,
            category: 'other',
            time: '2018-03-02T10:33:00.000Z'
          }
        ];

,我需要过滤o根据“重复键”缩小数组,让我们说 sourceAccount:“ A”,targetAccount:“ C”,金额:250,我需要使用重复的对象创建一个新的对象数组。希望使用纯JS!

编辑

期望值

var expected = [
          {
            id: 3,
            sourceAccount: 'A',
            targetAccount: 'B',
            amount: 100,
            category: 'eating_out',
            time: '2018-03-02T10:34:30.000Z'
          },
          {
            id: 1,
            sourceAccount: 'A',
            targetAccount: 'B',
            amount: 100,
            category: 'eating_out',
            time: '2018-03-02T10:33:00.000Z'
          },
          {
            id: 4,
            sourceAccount: 'A',
            targetAccount: 'B',
            amount: 100,
            category: 'eating_out',
            time: '2018-03-02T10:36:00.000Z'
          },
          {
            id: 2,
            sourceAccount: 'A',
            targetAccount: 'B',
            amount: 100,
            category: 'eating_out',
            time: '2018-03-02T10:33:50.000Z'
          }
        ];

到目前为止,我所有的意图都需要指定键的值,但是它可以是动态的,所以这个想法是将数组映射到一个新的数组中,其中sourceAccount,targetAccount,category和amount是相同的值,而没有之前知道价值。

2 个答案:

答案 0 :(得分:1)

您可以使用过滤器方法

var newArray = transactions.filter(f => f.sourceAccount =='A' && f.targetAccount == 'C' && f.amount == 250)

它将返回具有符合条件的所有对象的数组

答案 1 :(得分:1)

将匿名方法传递给返回true或false方法的javascript过滤器,可使您一次减少对象:

var done = new Set()
transactions.filter(obj => {
  if (!done.has(obj.id)) {
    done.add(obj.id)
    return true
  } else {
    return false
  }
})