1

How we can get the specific key value which is dynamically created, like

car object is dynamic like

 var car = {type:"Fiat", model_2017:"500", color:"white"};
 var car = {type:"Fiat", model_2016:"500", color:"white"};
 var car = {type:"Fiat", model_2015:"500", color:"white"};

How to get the value of second field, which is dynamic, i'm trying like this but it is giving undefined

var model_year=2015;
model_year= "model_"+model_year
car.model_year
Mehar
  • 2,158
  • 3
  • 23
  • 46

1 Answers1

2

You can try accessing with [] syntax

car[model_year]

var car = {type:"Fiat", model_2017:"500", color:"white"};
var car = {type:"Fiat", model_2016:"500", color:"white"};
var car = {type:"Fiat", model_2015:"500", color:"white"};

var model_year=2015;
model_year= "model_"+model_year
console.log(car[model_year])
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307