-1

how to get data from object with define string?

case:

  var data = [
  {name:"Sharma",country:"India"},
  {name:"Udin",country:"Indonesia"},
  {name:"John Carter",country:"Mars"}
  ];

  getData(data,"country");

  function getData(data,element){
    console.log(data[1].element);
  }

i want to get country but result is undefinded, how to fix this?

Abu Ayyub
  • 401
  • 4
  • 14

2 Answers2

2

You would need to know both the index and the property

function getData(data,index,element){
    console.log(data[index][element]);
}

getData(data,1,"country");
Ibu
  • 42,752
  • 13
  • 76
  • 103
  • 2
    You will need to index into the array still (`data` is an array) - perhaps he should have a parameter specifying the index...? – RB. Feb 01 '17 at 00:20
  • 1
    You are right, I misread the question.**Updated** – Ibu Feb 01 '17 at 00:20
1
function getData(data,element){
    console.log(data[1][element]);
  }

That's the correct way to access the value by using a key that is a string.

JohanP
  • 5,252
  • 2
  • 24
  • 34