-1

I have an array of car objects:

[
  {
    id: 1,
    make: "Honda",
    model: "Civic",
    style: "Coupe"
  },
  {
    id: 2,
    make: "Toyota",
    model: "Corolla",
    style: "Sedan"
  },
  {
    id: 3,
    make: "Subaru",
    model: "Forester",
    style: "Hatchback"
  },
]

Ex: I can use the bracket notation to search by the key

cars.map(car => car["make"])

// Returns an array of the make ["Honda", "Toyota", "Subaru"], as expected

Which leads me to believe, if I try to make a generic function that can pass the key as a property, which in theory should return the same thing.

Typo updated (It was correct on my application):

function DisplayItems(desiredKey) {
  return cars.map(car => car[desiredKey])
}

// Call it at a later point
DisplayItems("make")

// This is returning undefined

Why is this returning undefined?

Mitchell
  • 111
  • 15

1 Answers1

1

You have a syntax error when defining the DisplayItems function.

It should be defined like this:

function DisplayItems(desiredKey) {

without = before {

geesebump
  • 31
  • 4
  • You are correct. That was a typo, but still after fixing it, I am getting undefined whenever I fill in a value for `desiredKey` It actually comes back as `[undefined, undefined, undefined]` – Mitchell Mar 18 '23 at 17:43