skip to Main Content

I want to get the value of a property from an array of objects using the value of another property let’s say I have the following array:

const objArray = 
  [
    {car: 'BMW', price: 2000},
    {car: 'VW', price: 3500}, 
    {car: 'FORD', price: 4000}
 ]

Is it possible to access (get) the price using the car value ?
Something like: objArray.car[‘BMW’].price ?

2

Answers


  1. Is this meet your demand?
    In my opinion,the car must store in a variable or pass it as a parameter

    const objArray = 
      [
        {car: 'BMW', price: 2000},
        {car: 'VW', price: 3500}, 
        {car: 'FORD', price: 4000}
     ]
     
    let price = objArray.filter(a => a.car =='VW').map(e => e.price)[0]
    console.log(price)
    Login or Signup to reply.
  2. const objArray = 
      [
        {car: 'BMW', price: 2000},
        {car: 'VW', price: 3500}, 
        {car: 'FORD', price: 4000}
     ]
     
     function costByMake(make) {
       return (objArray.find(o => o.car === make) || {price: 0}).price
     }
     
     console.log(costByMake('VW'))
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search