2017-09-13 41 views
1

我有一大堆對象的數組,我想使用過濾器來獲得特定的對象,但我用下面的代碼得到數組。過濾器ES6返回數組,而不是對象

const target = [{ 
 
    name: 'abc', 
 
    id: 1 
 
}, { 
 
    name: 'def', 
 
    id: 2 
 
}] 
 

 
const x = target.filter(o => o.id === 1) 
 
console.log(x)

+5

因爲'array.filter'總是返回'array'(所有經過濾項的陣列),使用'array.find'以獲得單個對象。 –

+1

請改變你的標題,因爲你得到一個數組作爲'filter'的結果。 –

+0

@MayankShukla多數民衆贊成的信息。我同時使用過濾器,並找到了很多次,但從來沒有實現:) –

回答

0

Array.prototype.filter將返回從原始陣列,其通過測試功能包含數組元素。

如果你確信ID是唯一簡單地做X [0]來獲得結果。

+1

如果數組很大,它會只是浪費時間:'filter'遍歷所有元素,即使結果已經找到。但是,find找到結果後立即停止。 – raina77ow

4

如說,在評論,filter不會讓你從一個數組得到一個特定的對象 - 它只是返回另一個數組的元素滿足給定謂詞。你實際需要的是Array.prototype.find()。引述DOC:

find()方法返回第一個元件的滿足所述提供的測試功能的陣列 中的值。否則undefined返回的是 。

所以,你的代碼如下所示:

const target = [{ 
 
    name: 'abc', 
 
    id: 1 
 
}, { 
 
    name: 'def', 
 
    id: 2 
 
}]; 
 

 
const x = target.find(o => o.id === 1); 
 
console.log(x); // {name: "abc", id: 1}

0

array.filter總是返回數組。但你可以嘗試這個 -

const target = [{ 
 
     name: 'abc', 
 
     id: 1 
 
    }, { 
 
     name: 'def', 
 
     id: 2 
 
    }] 
 
    
 
let obj = {}  
 
const x = target.filter((o, index) => { 
 
    if(o.id === 1) 
 
    obj = target[index] 
 
}) 
 
console.log(obj)

相關問題