Passing in Dynamic Key:Value Pairs to an Object Literal

Passing in dynamic key:value pairs to an object literal?

EDIT: Use var obj = {}; obj[key] = chunks[i];

Because ECMAScript treats the key in this {key:1} as literal.

Creating object with dynamic keys

In the new ES2015 standard for JavaScript (formerly called ES6), objects can be created with computed keys: Object Initializer spec.

The syntax is:

var obj = {
[myKey]: value,
}

If applied to the OP's scenario, it would turn into:

stuff = function (thing, callback) {
var inputs = $('div.quantity > input').map(function(){
return {
[this.attr('name')]: this.attr('value'),
};
})

callback(null, inputs);
}

Note: A transpiler is still required for browser compatiblity.

Using Babel or Google's traceur, it is possible to use this syntax today.


In earlier JavaScript specifications (ES5 and below), the key in an object literal is always interpreted literally, as a string.

To use a "dynamic" key, you have to use bracket notation:

var obj = {};
obj[myKey] = value;

In your case:

stuff = function (thing, callback) {
var inputs = $('div.quantity > input').map(function(){
var key = this.attr('name')
, value = this.attr('value')
, ret = {};

ret[key] = value;
return ret;
})

callback(null, inputs);
}

dynamic keys for object literals in Javascript

You can set dynamic keys is with bracket notation:

required.directories[this.applicationPath + "/configs"] = "Application config folder does not exists";

(of course wherever you do this definition, this.applicationPath must exist)

But do you need this.applicationPath in the keys? How do you access theses values? Maybe you can just remove this.applicationPath from whatever value you use to access the properties.


But in case you need it:

You could use an array to initialize the keys if you want to avoid repeating a lot of code:

var dirs = ['configs', 'controllers', ...];
var files = ['init.js', 'controllers/index.js', ...];

var required = { directories: {}, files: {} };
required.directories[this.applicationPath] = "Application " + this.application + " does not exists";

for(var i = dirs.length; i--;) {
required.directories[this.applicationPath + '/' + dirs[i]] = "Application " + dirs[i] + " folder does not exists";
}

for(var i = files.length; i--;) {
// same here
}

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.

Dynamic object literal in javascript?

for ( var i = 0, l = arr.length; i < l; ++i ) {
literal[arr[i]] = "something";
}

I also took the liberty of optimising your loop :)

How can I add a key/value pair to a JavaScript object?

There are two ways to add new properties to an object:

var obj = {
key1: value1,
key2: value2
};

Using dot notation:

obj.key3 = "value3";

Using square bracket notation:

obj["key3"] = "value3";

The first form is used when you know the name of the property. The second form is used when the name of the property is dynamically determined. Like in this example:

var getProperty = function (propertyName) {
return obj[propertyName];
};

getProperty("key1");
getProperty("key2");
getProperty("key3");

A real JavaScript array can be constructed using either:

The Array literal notation:

var arr = [];

The Array constructor notation:

var arr = new Array();

Using Dynamic Value to add Object to Array with the Spread Operator

In ES6 what you can do is you can put the dynamic key inside brackets. So

const updatedItemsArr = [...this.state.targetItems, {[fieldType]: value}];

should work.

Is it possible to add dynamically named properties to JavaScript object?

Yes.

var data = {    'PropertyA': 1,    'PropertyB': 2,    'PropertyC': 3};
data["PropertyD"] = 4;
// dialog box with 4 in italert(data.PropertyD);alert(data["PropertyD"]);


Related Topics



Leave a reply



Submit