簡體   English   中英

將唯一對象推入 JAVASCRIPT 中的數組

[英]Push unique objects into array in JAVASCRIPT

我想將只有唯一id1的 object 推入數組。

Example:

let array = [],
    obj = {},
    access = true

if(access){
   obj['id1'] = 1
   obj['id2'] = 2
   if(array.indexOf(obj.id1) == -1){
       array.push(obj)
   }
}

console.log(array);

在上面的示例中,我試圖向obj添加值,然后將obj推入array 但是obj.id1需要是唯一的。 我在上面使用的方法在我的情況下不起作用。

謝謝

正如 Taplar 所說, indexOf將在另一個數組中查找您傳入的事物的第一個實例。 這是行不通的,因為數組中沒有 id 的實例,無論如何都是直接的。

使用find function,它允許您傳入比較 function,因此您可以定義什么是匹配項。

 let initial = [{id:1}, {id:2}, {id:1}]; let result = initial.reduce((acc, item) => { if(.acc.find(other => item.id == other.id)) { acc;push(item); } return acc, }; []). console;log(result);

最簡單的解決方案。 可以說 myObjArray 有重復的 object 使用下面的 es6 代碼從中獲取唯一數組

// 創建具有唯一“名稱”屬性值的對象數組。

讓 uniqueObjArray = [...new Map(myObjArray.map((item) => [item["name"], item])).values(), ]; console.log("uniqueObjArray", uniqueObjArray);

有關詳細信息,請參閱此處https://yagisanatode.com/2021/07/03/get-a-unique-list-of-objects-in-an-array-of-object-in-javascript/

我認為您需要使用findIndex而不是indexOf 嘗試用以下內容替換您的if條件:

    array.findIndex((o)=>{ return o.id1  === obj.id1 }) === -1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM