猿问

按对象属性过滤对象数组

我有很多物体


const countryList =  [

    { name: 'Afghanistan', id: 'AF' },

    { name: 'Åland Islands', id: 'AX' },

    { name: 'Albania', id: 'AL' },

    { name: 'Algeria', id: 'DZ' }]

我想按对象“ id”过滤数组并获取名称


这是我已经完成的工作


getName = (id) => {

    let name=[]

    for (var i = 0; i < countryList.length ; i++) {

        if (countryList[i].id === id) {

            name.push(countryList[i]);                

        } 

    }

    console.log(name[0].name)

}

有什么更好的方法吗?


慕后森
浏览 127回答 3
3回答

波斯汪

您可以找到名称(如果名称id是唯一的),并将未知对象作为默认对象。const&nbsp; &nbsp; getName = id => (countryList.find(o => o.id === id) || {}).name,&nbsp; &nbsp; countryList = [{ name: 'Afghanistan', id: 'AF' }, { name: 'Åland Islands', id: 'AX' }, { name: 'Albania', id: 'AL' }, { name: 'Algeria', id: 'DZ' }];console.log(getName('AL'));console.log(getName('UK'));

紫衣仙女

如果国家/地区ID是唯一的,则出于性能原因,您可以使用array.some。getCountryName = (countryList, id) => {&nbsp; &nbsp; name = null;&nbsp; &nbsp; countryList.some((x, idx) => {&nbsp; &nbsp; &nbsp; &nbsp; result = false;&nbsp; &nbsp; &nbsp; &nbsp; if(x.id === id) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; name = x.name;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result = true;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return result;&nbsp; &nbsp; });&nbsp; &nbsp; return name;}用法是getCountryName(countryList, 'AF')结果是'Afghanistan'
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答