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.

5
  • An object can have any number of properties, so "the key" doesn't really make sense in general. Commented Feb 26, 2019 at 0: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 Commented Feb 26, 2019 at 0:27
  • An array of objects with different keys is a code smell. Commented Feb 26, 2019 at 0: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. Commented Feb 26, 2019 at 0: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! Commented Feb 26, 2019 at 2:06

2 Answers 2

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!')
});

Sign up to request clarification or add additional context in comments.

Comments

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!')
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.