Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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)

share|improve this question

marked as duplicate by Felix Kling, Stewie, Endoro, Hanlet Escaño, Sunil D. Jun 23 '13 at 23:14

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

2 Answers 2

up vote 4 down vote accepted

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 :(

share|improve this answer
    
Perfect understanding now, thank you! –  Fezzik Jun 23 '13 at 16:06
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.)

share|improve this answer
    
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

Not the answer you're looking for? Browse other questions tagged or ask your own question.