1

I'm running this code.

var output = {"records": []};
for(i = 0; i < data.length; i++)
  output.records[i] = { propertyName : data[i][propertyName] }

I expected the output to be on the following form.

{ "cat" : "mjau" }
{ "dog" : "woff" }

Instead, I get to my surprise this.

{ "propertyName" : "mjau" }
{ "propertyName" : "woff" }

How can I get variable propertyName?

I'm trying to create a parser that will create a number of records that are all cat but, when called from an other place, the records should have dog property instead. I wish to avoid creating two different code pieces for that.

I've found this question, which I suspect contains the answer to my issue. However, due to ignorance, I don't get it.

Community
  • 1
  • 1
  • where do you put those cat n dog?? i mean where do you hold those properties? – Bhushan Firake Dec 10 '12 at 20:30
  • possible duplicate of [creating json object with variables](http://stackoverflow.com/questions/12979335/creating-json-object-with-variables) – jbabey Dec 10 '12 at 20:30
  • @jbabey Congrats! I mentioned in my question that I found **that exact question**. I also explained that due to lack of skills, I don't understand it. What's the point of mentioning it **again**? Besides, the answers I got here are very clear and actually helpful, so **exact** duplicate it is not. :) –  Dec 10 '12 at 20:39
  • @BhushanFirake I'm not sure what you mean. Those are just some property names that I'll be working with. –  Dec 10 '12 at 20:44

4 Answers4

3

Keys in object literals won't be evaluated in JavaScript. So, you need to create an empty object ({}) and then assign the key dynamically:

output.records[i] = {};
output.records[i][propertyName] = data[i][propertyName]
Wyatt Anderson
  • 9,612
  • 1
  • 22
  • 25
0
var a = {b:'c'}

is just like

var a = {};
a['b'] = 'c';

What you want is

a[b] = c

that is

output.records[i] = {};
output.records[i][propertyName] = data[i][propertyName];

You have in this MDN document : Working with objects.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
0

In { propertyName : data[i][propertyName] } the property name part should be constant string. It you pass a variable it wont fetch its value.

What you have to do is

for(i = 0; i < data.length; i++){
  var a = {};
  a[propertyName] = data[i][propertyName];
  output.records.push(a);
}
Shiplu Mokaddim
  • 56,364
  • 17
  • 141
  • 187
-1

You can try this:

'"' + propertyName + '"' : ...
orolo
  • 3,951
  • 2
  • 30
  • 30
  • I notice that your approach is different from most of the others. Is it the same thing expressed with an other syntax or is it a different method? If so, which is preferable in this case? –  Dec 10 '12 at 20:41
  • No. I misunderstood. All I'm doing in the above is wrapping the string in quotes. OP would probably get something like ""propertyName"". – orolo Dec 10 '12 at 21:55