2

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.

ilikechocolate
  • 193
  • 1
  • 12
  • An object can have any number of properties, so "the key" doesn't really make sense in general. – Pointy Feb 26 '19 at 00:23
  • Can you add more context about what you want do with the keys? For example, if you're inspecting the keys and values, maybe you should use `Object.entries` – Sidney Feb 26 '19 at 00:27
  • An array of objects with different keys is a code smell. – Barmar Feb 26 '19 at 00:29
  • 3
    It would be better if it were something like `[{ fruit: 'apple', color: 'red'}, {fruit: 'banana', color: 'yellow'}]. Variable data should be in values, not keys. – Barmar Feb 26 '19 at 00:32
  • 1
    @Barmar Yeah I changed my design similar like what you said, it's way much easier to get the info I need. Thank you! – ilikechocolate Feb 26 '19 at 02:06

2 Answers2

1

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!')
});
Ele
  • 33,468
  • 7
  • 37
  • 75
1

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!')
})
Code Maniac
  • 37,143
  • 5
  • 39
  • 60