-3

i have a question here: why cant i use "." instead of "[]",to call a property of the object??

function filter(array, prop) {

  var result = array.map(x=>{
    return x[prop]
  })

  return result
}

filter([{ name: 'TV LCD', price: 100}, { name: 'PC', price: 500 }],"name")

//[ 'TV LCD', 'PC' ]

 function filter(array, prop) {

  var result = array.map(x=>{
    if(x.name===prop){
      return x
    }
  })

  return result
}

filter([{ name: 'TV LCD', price: 100}, { name: 'PC', price: 500 }],"name")


//[undefined,undefined]

sorry for my english :/

i want the "name" property of the object, but in the console shows: [undefined,undefined]

Raymond Chen
  • 44,448
  • 11
  • 96
  • 135
Bytexr
  • 3
  • 1

1 Answers1

1

Because x.name is "TV LCD" or "PC" and prop is "name", so x.name === prop never evaluates to true.

if(x.name===prop){ // x.name is never "name"; always evaluates to false
  return x
}

The syntax below is the equivalent of x["name"] which is the same as x.name.

return x[prop]
ray
  • 26,557
  • 5
  • 28
  • 27
  • I did some research and found that it is related to the [bracket notation], i suppose it is for the iteration of the .map() ty btw – Bytexr Jun 03 '23 at 18:51