2017-04-19 45 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; 
相关问题