ilikechocolate
ilikechocolate

Reputation: 209

get keys from object javascript

Here is what I have:

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

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

I want to ask is there a simple way for me to get the key? I feel I was making it too complicated by using

Object.key(field)[0]

add: I am just trying to get each key from this array of object and compare with a string.

Upvotes: 2

Views: 83

Answers (2)

Code Maniac
Code Maniac

Reputation: 37775

You can simply use destructuring assignment

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

fields.forEach( e => {
    let [key] = Object.keys(e)

    if (key === 'apple')
      console.log('works!')
})

Upvotes: 1

Ele
Ele

Reputation: 33736

You should use includes to check if apple is within the array 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!')
});

Upvotes: 1

Related Questions