0

i want to get property value from javascript object list, i have a list

var cars = [{ id: 1, name: 'Audi' }, { id: 2, name: 'BMW' }, { id: 1, name: 'Honda' }];

Now i want get id or name property value by using for loop like this

var cars = [{ id: 1, name: 'Audi' }, { id: 2, name: 'BMW' }, { id: 1, name: 'Honda' }];
 var items=[];
 var firstProp='id';
 for (var i = 0; i < model.length; i++) {

  //original work
  items.push({ value: model[i].firstProp});//here is the problem
 }

please give good advise, thanks.

Shohel
  • 3,886
  • 4
  • 38
  • 75
  • hi, @cookiemonster, no duplicate here. – Shohel Jul 13 '14 at 05:33
  • 2
    What do you mean "no duplicate here"? It's exactly what you need. Same question. Same issue. Same answer. – cookie monster Jul 13 '14 at 05:35
  • ...or if you're not happy with that duplicate, you'll find many others if you [use Google](https://www.google.com/search?num=50&q=javascript+get+object+property+using+variable+site%3Astackoverflow.com&oq=javascript+get+object+property+using+variable+site%3Astackoverflow.com). – cookie monster Jul 13 '14 at 05:36
  • ...notice also that the solution is even in your question. `model[i]` is using a variable to access the property of an object. And yes, I know it's an Array. Arrays are Objects in JavaScript. – cookie monster Jul 13 '14 at 05:39

2 Answers2

1

If I understand your problem correctly, you should use square bracket notation instead of dot notation:

//..  
items.push({ value: model[i][firstProp]});//here is the problem
Andrius
  • 947
  • 15
  • 22
  • Yes you are correct from what I see from the OP's post `model[i].firstProp` is calling the property `firstProp` and not `id` as assigned to that variable though it would just be easier to use `model[i].id` – EasyBB Jul 13 '14 at 05:39
0

You should do like this

items.push({ value: model[i][firstProp]});

the . notation expects the firstProp to be present as a key in dictionary, since the firstProp is a variable that contains a string you should use [] notation.

cookie monster
  • 10,671
  • 4
  • 31
  • 45