2017-04-19 46 views
0

我知道我的描述有點混亂內的另一個價值,但讓我解釋一下你: 我有對象的數組喜歡這樣的: [{name: Alex, last: Huros}, {name: Mitsos, last: Mitsou},name: Bill, last: Hurosis ]找對象的數組中的元素,如果你知道對象

我有一個變量值爲const name = Alex。現在我想找到最後名字=亞歷克斯。更具體地說,我想以某種方式或一般名稱找到名稱= Alex,因爲我想找到名字的最後一個名字。這個怎麼做?我試過array.forEach和找到,但沒有工作,我用它

+1

使用'find'。 'arr.find(o => o.name ==='Alex')。last'。 – Tushar

回答

1

您應該使用find方法,它返回滿足提供callback功能數組中的第一個元素的值的方式。否則返回undefined

var array=[{"name": "Alex", "last": "Huros"}, {"name": "Mitsos", "last": "Mitsou"},{"name": "Bill", "last": "Hurosis" }] 
 
console.log(array.find(function(person){ 
 
    return person.name=="Alex"; 
 
}).last);

或者乾脆用arrow功能。

var last = array.find(p => p.name === 'Alex').last; 
相關問題