[英]check for duplicates in multiple fields in array of objects based on condition in javascript
[英]How to check the duplicates property in array of objects based on condition javascript
我有 object arrayobj
數組,其中必須檢查的屬性值
javascript中基於條件返回語句的code
和type
no add
或can add
在 arrobj for type-local, if type local and code values not reappearing in other object
返回“可以添加”,否則返回“不添加”
在 arrobj for type-FL or FL Travel, if different type and code values reappearing in other object
返回 '可以添加'
在 arrobj for type-FL or FL Travel if type and code both reappearing in object
返回“不添加”
如何在javascript中查看以上情況,
在不檢查屬性type
的情況下嘗試了代碼,卡住了
function checkValues(arrob){
const checkcode = arrob.map(elem => elem.code);
if (arrob.length !== new Set(checkcode).size) {
return "no add";
} else {
return "can add"
}
}
checkValues(arrobj1);
checkValues(arrobj2);
checkValues(arrobj3);
sample objects for scenario
var arrobj1=[
{id:1, name: "ram", code: "NIXZ", type: "Local"},
{id:2, name: "abey", code: "ABCN", type: "FI"},
{id:3, name: "jaz", code: "ABCN", type: "FI Travel"}
]
var arrobj2=[
{id:1, name: "ram", code: "NIXZ", type: "Local"},
{id:4, name: "zain", code: "NIXZ", type: "FI"},
{id:2, name: "abey", code: "ABCN", type: "FI"},
{id:3, name: "jaz", code: "ABCNE", type: "FI Travel"}
]
var arrobj3=[
{id:1, name: "ram", code: "NIXZ", type: "Local"},
{id:4, name: "sam", code: "ABCN", type: "FI"},
{id:2, name: "abey", code: "ABCN", type: "FI"},
{id:3, name: "jaz", code: "ABCNE", type: "FI Travel"}
]
預期結果
//for arrobj1 [type-FL or FL Travel, different type and same code appears]
can add
//for arrobj2 [type local, same code appears]
no add
//for arrobj3 [type-FL or FL Travel, same type and same code appears]
no add
map() 方法創建一個新數組,其中填充了對調用數組中每個元素調用提供的 function 的結果。
const rawArray = [arrobj1 , arrobj2 , arrobj3]
const hasDups = (objArray) => {
objArray.ForEach(el => {
if (objArray.Includes(el.type))
return true;
return false;
});
}
const newArray = rawArray.map(el => !hasDups(el));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.