[英]JS - Getting object property value
是否可以在后面的一段代碼中動態獲取任何屬性值,其名稱是我們無法預測的?
通過 object['keyName'] 獲取值不適合這里,因為我們不知道屬性名稱。
我們的屬性名稱可以是 ANY 且不可預測。
let arr = [{a: 'a'}, {b: 'b'}];
let filtered = [];
filtered = arr.filter(item => {
return item.'some property' === 'a';
});
您可以使用Object.values()
獲取值的數組,然后使用Array.includes()
檢查是否在數組中找到請求的值:
const arr = [{a: 'a'}, {b: 'b'}]; const filtered = arr.filter(item => Object.values(item) // get an array of values from the object ['a'] or ['b'] in this case.includes('a') // check if the array of values contains 'a' ); console.log(filtered)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.