jeudi 22 octobre 2020

How to return the key of an array of objects using its name

NOTE: I know what I'm attempting to do logically doesn't make sense in terms of why I want to achieve this, however I just want to know if it's possible and if so what I might be writing wrong?

I'm working with an array of objects like so:

this.animalsAndFruits = [
  {
    "category": "Apple",
    "num1": 1287,
    "num2": 12956
  },
  {
    "category": "Panda",
    "num1": 2574,
    "num2": 25826
  },
  ....
]

This may seem tedious and rather ridiculous however using the array I want to return the word 'category', not the value just the key 'category'.

I've tried

this.objectFromArray[0].category

However it only returns the value of the 0th indexed item (even though the 0th indexed item key will always have key 'category')

Is there another way I can accomplish this?

P.S. The reason why I want to get 'category' is because I need to set a variable = 'category', however I don't want to hardcode it directly like this

var someVar  = 'category'

If it helps, the value in the key:value pair where the key = category is always a string (whereas all of the other values under different keys are numbers.

Maybe logic like so might work =>

if(value = string) then return key  ?

Aucun commentaire:

Enregistrer un commentaire