如何检查数组中的多个对象是否具有相同的属性值?

时间:2019-05-06 14:48:59

标签: javascript

嘿,我想知道在我的案例dueTo中检查两个或多个对象是否具有相同属性值的最佳方法是什么?

我的数组看起来像这样

Array [
  Object 
    "__typename": "Instalment",
    "_id": "5cd022cf0d805222374197eb",
    "description": "Description",
    "dueTo": "2019-05-16T23:00:00.000Z",
    "instalmentAmount": 200000,
    "paid": false,
  },
  Object {
    "__typename": "Instalment",
    "_id": "5cd022cf0d805222374197ea",
    "description": "Description",
    "dueTo": "2019-05-23T23:00:00.000Z",
    "instalmentAmount": 200000,
    "paid": false,
  },
  Object {
    "__typename": "Instalment",
    "_id": "5cd022cf0d805222374197e9",
    "description": "Description",
    "dueTo": "2019-05-23T23:00:00.000Z",
    "instalmentAmount": 200000,
    "paid": false,
  },
]

首先,我想知道哪些对象包含值paid: false

const unpaidInstalments = instalments.filter(
  instalment => !instalment.paid
);

现在,我想检查在同一天是否有分期付款的情况,这将导致索引1和2出现,这里出现的问题是如何过滤此索引?

已解决

获取所有可用日期并将其放在一个对象中,然后检查是否有多个对象包含相同的值,并返回包含这些对象的数组

const sameDayArray = unpaidInstalments.reduce(
  (datesToCheck, instalment) => {
    datesToCheck[instalment.dueTo] =
      (datesToCheck[instalment.dueTo] || 0) + 1;
    return datesToCheck;
  },
  {}
);

const instalmentsSameDay = unpaidInstalments.filter(instalment => {
  return sameDayArray[instalment.dueTo] > 1;
});

0 个答案:

没有答案