3

saw a few answers related to this, but none answer this version of the subject in question.

Consider the following: (linkto: jsfiddle)

$(function(){

arrKeys = [];
objArr = [];

nameArr = ['name1','name2','name3','name4'];
descArr = ['desc1','desc2','desc3','desc4'];
allValues = {name:  nameArr, desc: descArr};

arrKeys[0] = 'name';
arrKeys[1] = 'desc';

    first = arrKeys.shift(); // returns 'name'

    $(allValues[first]).each(function (key,value) { 

        console.log(first); //returns 'name'
        objArr[key] = {first:value}; //the problem

    });

    console.log(objArr);


});

With console.log(objArr) producing the following array of objects like so:

[Object, Object, Object, Object] 0: Object first: "name1" 1: Object first: "name2" 2: Object first: "name3" 3: Object first: "name4" length: 4

The issue is that I'd like the property "first" to be the value of the var first (which is "name".. So instead, the result would be:

[Object, Object, Object, Object] 0: Object name: "name1" 1: Object name: "name2" 2: Object name: "name3" 3: Object name: "name4" length: 4

(linkto: jsfiddle)

Fezzik
  • 45
  • 1
  • 3

2 Answers2

10

To set variables as key names you have to use bracket notation;

console.log(first); // returns 'name'
var obj = {};
obj[first] = value;
objArr[key] = obj; // no longer a problem

Sorry it's more verbose :(

Edit;

In ES6 you can now use computed-property-names;

const key = 'name';
const value = 'james';

const obj = {
  [key]: value
};
Ele
  • 33,468
  • 7
  • 37
  • 75
Jivings
  • 22,834
  • 6
  • 60
  • 101
2
var x = {}
x[first] = value
objArr[key] = x

Javascript object literal syntax treats unquoted keys as if they were quoted strings instead of variable names. You have to use bracket syntax to set properties with names computed at runtime.

(Why are you wrapping your code in a jQuery call? And you really should be using var declarations.)

user2357112
  • 260,549
  • 28
  • 431
  • 505
  • I'm not using those global vars, just when throwing that example together for this specific question. The jquery is nonessential. Thank you for your response. – Fezzik Jun 23 '13 at 16:05