[英]Iterate through object array and filter it based on multiple conditions
我有 object 數組,其中包含大量重復/無用的數據。 我需要根據客戶 ID 進行過濾,然后選擇最新日期的 object。 數據看起來像這樣:
let data = [
{
CUSTOMER_PERMANENT_ID: "2495",
EMAIL: "abs@gmail.com",
EVENT_ACTIVATION_TIME: "2019-10-25 13:57:38.79",
},
{
CUSTOMER_PERMANENT_ID: "2495",
EMAIL: "abs@gmail.com",
EVENT_ACTIVATION_TIME: "2019-10-28 20:04:49.016",
},
{
CUSTOMER_PERMANENT_ID: "2495",
EMAIL: "abs@gmail.com",
EVENT_ACTIVATION_TIME: "2019-10-28 20:04:49.019",
},
{
CUSTOMER_PERMANENT_ID: "5995",
EMAIL: "John@gmail.com",
EVENT_ACTIVATION_TIME: "2019-10-28 17:24:10.98",
}
]
我嘗試了以下 function,但它僅在有兩個重復對象時才有效,如果有兩個以上,則返回所有對象。
public fixDcppSelectedClientData() {
let result = [];
for (let item of this.arr) {
for (let checkingItem of this.arr) {
if (
this.arr.indexOf(item) !=
this.arr.indexOf(checkingItem) &&
item.CUSTOMER_PERMANENT_ID == checkingItem.CUSTOMER_PERMANENT_ID &&
new Date(item.EVENT_ACTIVATION_TIME).getTime() <
new Date(checkingItem.EVENT_ACTIVATION_TIME).getTime()
) {
if (result.indexOf(checkingItem) == -1) {
result.push(checkingItem);
}
}
}
}
console.log("filtered data is ", result);
}
我需要更多地研究這個話題,但是如果有人能在此期間提供幫助,那就太好了。
問候
let id = "2495"
const query = data
.filter( obj => obj.CUSTOMER_PERMANENT_ID === id )
.sort( (obj1, obj2) =>
(obj1.EVENT_ACTIVATION_TIME < obj2.EVENT_ACTIVATION_TIME) ? 1 : -1
)
console.log('latest', query[0]);
console.log('second to latest', query[1]);
console.log('all with this id', query)
此代碼過濾器重復 id
var newArr = data.filter((x, index, self) => index === self.findIndex((t) => ( t.CUSTOMER_PERMANENT_ID === x.CUSTOMER_PERMANENT_ID))); console.log(newArr);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.