2016-09-30 17 views
0

在selectItem數組中找到特定值請幫我瞭解如何在primeng SelectItem []數組中找到特定值。primeng:如何使用代碼

我有selectItem數組如下。

this.cities = []; 
    this.cities.push({label:'Select ', value:null}); 
    this.cities.push({label:'New York', value:{id:1, name: 'New York', code: 'NY'}}); 
    this.cities.push({label:'Rome', value:{id:2, name: 'Rome', code: 'RM'}}); 
    this.cities.push({label:'London', value:{id:3, name: 'London', code: 'LDN'}}); 
    this.cities.push({label:'Istanbul', value:{id:4, name: 'Istanbul', code: 'IST'}}); 
    this.cities.push({label:'Paris', value:{id:5, name: 'Paris', code: 'PRS'}}); 

我想從上面的列表中找到特定項目({id:5,name:'Paris',code:'PRS'})。或者我只想找到代碼爲'PRS'的物品。

回答

0

您可以使用以下任何一種方法。但最好的方法是'找到'。

尋找項目與值{ID:5,名稱: '巴黎',代碼: 'PRS'}

let obj = {id:5, name: 'Paris', code: 'PRS'}; 
var x = this.cities.find(item => 
    JSON.stringify(item.value) === JSON.stringify(obj) 
); 

console.log(x); 

OR

let obj = {id:5, name: 'Paris', code: 'PRS'}; 
this.cities.forEach((item,key) => { 
    if(item && JSON.stringify(item.value) === JSON.stringify(obj)) { 
     console.log("Item found at location : "+key) 
    } 
}); 

尋找與項目代碼'PRS'

this.cities.forEach((item,key) => { 
    if(item && item.value != null && item.value.code == 'PRS') { 
     console.log("Item found at location : "+key) 
    } 
});