簡體   English   中英

從對象 javascript 獲取密鑰

[英]get keys from object javascript

這是我所擁有的:

fields = [ { apple: 'red' }, { banana: 'yellow' } ]

fields.forEach(field => {
    // trying to get the key here
    if (Object.keys(field)[0] === 'apple')
        console.log('works!')
})

我想問一下有沒有簡單的方法讓我拿到鑰匙? 我覺得我使用它太復雜了

Object.key(field)[0]

添加:我只是想從這個對象數組中獲取每個鍵並與一個字符串進行比較。

您應該使用includes來檢查apple是否在數組Object.keys(field)

 let fields = [{ apple: 'red'}, { banana: 'yellow'}]; fields.forEach(field => { // trying to get the key here if (Object.keys(field).includes('apple')) console.log('works!') });

您可以簡單地使用解構賦值

 let fields = [ { apple: 'red' }, { banana: 'yellow' } ] fields.forEach( e => { let [key] = Object.keys(e) if (key === 'apple') console.log('works!') })

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM