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.

4
  • hi, @cookiemonster, no duplicate here. Commented Jul 13, 2014 at 5:33
  • 2
    What do you mean "no duplicate here"? It's exactly what you need. Same question. Same issue. Same answer. Commented Jul 13, 2014 at 5:35
  • ...or if you're not happy with that duplicate, you'll find many others if you use Google. Commented Jul 13, 2014 at 5: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. Commented Jul 13, 2014 at 5:39

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

1 Comment

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
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.