JavaScript Set Object Key by Variable

JavaScript set object key by variable

You need to make the object first, then use [] to set it.

var key = "happyCount";
var obj = {};

obj[key] = someValueArray;
myArray.push(obj);

UPDATE 2021:

Computed property names feature was introduced in ECMAScript 2015 (ES6) that allows you to dynamically compute the names of the object properties in JavaScript object literal notation.

const yourKeyVariable = "happyCount";
const someValueArray= [...];

const obj = {
[yourKeyVariable]: someValueArray,
}

How to use a variable for a key in a JavaScript object literal?

{ thetop : 10 } is a valid object literal. The code will create an object with a property named thetop that has a value of 10. Both the following are the same:

obj = { thetop : 10 };
obj = { "thetop" : 10 };

In ES5 and earlier, you cannot use a variable as a property name inside an object literal. Your only option is to do the following:

var thetop = "top";

// create the object literal
var aniArgs = {};

// Assign the variable property name with a value of 10
aniArgs[thetop] = 10;

// Pass the resulting object to the animate method
<something>.stop().animate(
aniArgs, 10
);

ES6 defines ComputedPropertyName as part of the grammar for object literals, which allows you to write the code like this:

var thetop = "top",
obj = { [thetop]: 10 };

console.log(obj.top); // -> 10

You can use this new syntax in the latest versions of each mainstream browser.

How can I dynamically set an objects keys to a variable using Javascript?

Not sure what exactly is you purpose, but this will do the transformation you want.

Object.keys(localStorage).reduce((acc,key)=>{
return[...acc,{id:key,value:localStorage[key]}]
},[])

Can I set Javascript object keys based on a variable, e.g index of a loop?

You could solve this by not putting artists directly in the object, like this, using a array inside a single attribute of the object:

{
"artists": [
{
"data": "data",
"moreData": "more-data"
},
{
"data": "data",
"moreData": "more-data"
}
],
"correctAnswer": 3
}

Or alternatively, if you really want a dynamic key you can use

{
[`artist${artistIndex}`]: {'data': 'data'}
}

Can I add a key-value pair to an object and have the key be equal to a variable?

Use Following code to use a variable as a key. Use [] operator to set the variable value to the key.

const key = "variableKey";

const object = {};

Object.assign(object, {[key]: 'value'});

How To Set A JS object property name from a variable

var jsonVariable = {};
for(var i=1; i < 3; i++) {
jsonVariable[i + 'name'] = 'name' + i;
}

React render object value where key is variable

To access values using computed property keys you need to use the bracket notation.

<CustomArrayHelper values={formValues.myObj[currentKey]} />

Also, you shouldn't put a dot when accessing properties using bracket notation, that's a syntax error. You can also remove the string template syntax, that's unnecessary.

formValues.myObj[currentKey].length

Is there a way to use variable keys in a JavaScript object literal?

In ES6, use computed property names.

const key = "anything";   

const object = {
[key]: "key attribute"
// ^^^^^ COMPUTED PROPERTY NAME
};

Note the square brackets around key. You can actually specify any expression in the square brackets, not just a variable.

JavaScript set anonymous Object key to variable name

You can do this:

var curr = data[i],
newArray = [],
key = curr.Frequency.Type,
obj = {};

obj[key] = [];
newArray.push(obj);

There's no way to do it in JavaScript within the object literal itself; the syntax just doesn't provide for that.

edit — when this answer was written, the above was true, but ES2015 provides for dynamic keys in object initializers:

var curr = data[i],
key = curr.Frequency.Type,
newArray = [ { [key]: [] } ];


Related Topics



Leave a reply



Submit