3 回答

TA貢獻1847條經(jīng)驗 獲得超7個贊
試試這樣:
getValueOfKey() {
for (var obj of this.data.participants) {
if(obj.hasOwnProperty('key')){
return obj.key;
}
}
}

TA貢獻1982條經(jīng)驗 獲得超2個贊
如果要檢查數(shù)組是否具有具有key屬性的對象,請使用some方法。如果要獲取數(shù)組中具有key屬性的所有對象,請使用filter方法:
const arr = [{
"dateJoin": 1520409578,
"dateLeft": 0,
"firstName": "edh",
"internalId": 165,
"invitedBy": "edh",
"lastName": "edh",
"userId": "edh",
"key": "data"
},
{
"dateJoin": 1520409578,
"dateLeft": 0,
"firstName": "",
"internalId": 166,
"invitedBy": "edh",
"lastName": "",
"userId": "ATB"
}];
const hasKey= arr.some(s => s.key);
console.log(`hasKey: ${hasKey}`);
const objectsWithKeyProperties = arr.filter(f => f.key);
console.log(`objectsWithKeyProperties :`, objectsWithKeyProperties);

TA貢獻1875條經(jīng)驗 獲得超5個贊
您可以使用過濾器Array.prototype.filter()從與您的過濾器匹配的數(shù)組中檢索所有元素。
該函數(shù)接受一個回調(diào)函數(shù)作為必須返回true以保留元素或false刪除元素的參數(shù)。該函數(shù)返回一個包含與過濾器匹配的所有元素的新數(shù)組:
const result = [1, 2, 3, 4, 5].filter((num) => num > 3);
// result will look like this: [4, 5]
對于您的問題,您將檢查所需的屬性是否為undefined:
participants.filter((participant) => participant.key !== undefined);
此函數(shù)將返回一個新數(shù)組,其中包含所有具有名為key的屬性的對象。
我們可以使用一些 Javascript 魔法來縮短事件并省略!== undefined檢查,因為在一個if條件下,undefined等于 false 并且任何其他結(jié)果(除了 boolean false)等于true:
participants.filter((participant) => participant.key);
片段:
console.log([1, 2, 3, 4, 5].filter((num) => num > 3));
const participants = [
{name: "John", key: "zero"},
{name: "Prince"}
];
console.log(participants.filter((participant) => participant.key));
添加回答
舉報