This question already has answers here:
dynamic keys for object literals in Javascript [duplicate]
(8 answers)
How do I interpolate a variable as a key in a JavaScript object?
(6 answers)
Closed 9 years ago.
In JavaScript, is there a shorter way to create object from a variable then below.
var d = 'something';
function map(d){
var obj = {};
obj[d] = d;
return obj;
}
well, the shortest looks like, but it is wrong as key is literal d than its value.
function wrong(d){
return {d:d}
}
I don't mind the first version, but wonder any succinct way.
thanks.
I recommend instantiating an anonymous function.
function map(d) {
return new function () {
this[d] = d;
};
}
Using an anonymous function will allow you to keep all of your property declarations in the same place to be more organized. If you need other default keys set you can add them easily:
new function () {
this[d] = d;
this.foo = 'bar';
};
Versus with an object literal you'll have declarations in two places:
obj = {
foo: 'bar'
};
obj[d] = d;
That all said, the original code is fine as-is. It's concise, readable, and maintainable.
function map(d) {
var obj = {};
obj[d] = d;
return obj;
}
Related
This question already has answers here:
How does this object method definition work without the "function" keyword?
(2 answers)
Closed 6 years ago.
I entered this expression in the Firefox and Chrome Dev Console and I wonder why it is valid JavaScript:
var x = { a (b) {} };
console.log(x);
x is then set to an object with the property "a" containing a function called "a" with an argument identifier "b".
How is this valid JavaScript syntax? The colon is missing after "a" and I do not understand the function definition.
This is ES6 / ES2015 syntactic sugar (Property shorthand).
With ES6:
const obj = {
a(b) {
// Shorthand method
// `this` context is `obj`
},
c
};
is equal to
var obj = {
a: function a(b) {
},
c: c
};
In JavaScript, when you write:
var x = { a (b) {} };
It will consider it as:
var x = {
a: function (b) {
}
}
For example, you can check this and it will clear your doubt:
var x = { a (b) { console.info('function called') } };
x.a();
This will call the function which is assigned to property a of object x.
This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 7 years ago.
I know that you can evaluate the value of a property inside of a JS object, like the following:
let object = {
value: 5+5
};
I am wondering if there is any possible way to evaluate the name of an attribute with JS, i.e. achieve the following:
let object;
object[5+5].value = "ten";
As something like:
let object = {
5+5: "ten"
};
Yes in ES2015, no in ES5, but first let's clear one thing up: that's JavaScript, not JSON.
In ES2015 (formerly known as ES6):
var something = "foo";
var object = {
[something]: "bar";
};
alert(object.foo); // "bar"
Inside the [ ] can be any expression you like. The value returned is coerced to a string. That means you can have hours of fun with stuff like
var counter = function() {
var counter = 1;
return function() {
return counter++;
};
};
var object = {
["property" + counter()]: "first property",
["property" + counter()]: "second property"
};
alert(object.property2); // "second property"
JSON is a serialization format inspired by JavaScript object initializer syntax. There is definitely no way to do anything like that in JSON.
Sure. Try this:
'use strict';
let object = {
[5+5]: "ten"
};
console.log(object); // Object {10: "ten"}
This question already has answers here:
how to access object property using variable [duplicate]
(2 answers)
Closed 7 years ago.
I am trying to use a variable to select from an array:
This works:
var myarray = {bricks:3000, studs:500, shingles:400, tiles:700};
function One() {
alert(myarray.bricks);
}
But this does not work:
var myarray = {bricks:3000, studs:500, shingles:400, tiles:700};
var myvalue = "bricks"
function Two() {
alert(myarray.myvalue);
}
How do I do this properly? Here is a fiddle to show what I am trying to accomplish: https://jsfiddle.net/chrislascelles/xhmx7hgc/2/
Use the [] notation.
var myarray = {bricks:3000, studs:500, shingles:400, tiles:700};
function One() {
alert(myarray.bricks);
}
var myvalue = "bricks" //supplied here to make example work
function Two() {
alert(myarray[myvalue]);
}
Demo
The variable is not an array, it's an object.
To access an element from object using variables you should use Bracket Notation like bellow
alert(myarray[myvalue]);
Fiddle
The only thing you are lacking is the syntax. Here is how it works:
function Two() {
alert(myarray[myvalue]);
}
In javascript, it means the same thing to write these two:
var a = {};
a.foo = "hello";
a["bar"] = "world";
a.bar; // world;
a["foo"]; // hello;
This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Closed 7 months ago.
In PHP I can mess around with variable variables and I'm wondering if I can do the same in JavaScript.
I want to create a new object with a property which's name is based on the value of a variable.
if ( obj.name === 'foo' ) {
var data = { foo: value };
}
if ( obj.name === 'bar' ) {
var data = { bar: value };
}
Is there a shorter way of doing this without using eval()? Something like:
var data = { obj.name: value };
Try this:
var data = {};
data[obj.name] = value;
You can read some more about js objects Here.
Objects in JavaScript are simply hash maps. You can access members by indexing with their names. For your problem you can use
var data = {};
data[obj.name] = value;
I've used this to implement a dynamic dispatch mechanism for arithmetic operations on different numerical types as described here.
This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 8 years ago.
First off, I'm using Cheerio for some DOM access and parsing with Node.js. Good times.
Heres the situation:
I have a function that I need to create an object. That object uses variables for both its keys and values, and then return that single object. Example:
stuff = function (thing, callback) {
var inputs = $('div.quantity > input').map(function(){
var key = this.attr('name')
, value = this.attr('value');
return { key : value }
})
callback(null, inputs);
}
It outputs this:
[ { key: '1' }, { key: '1' } ]
(.map() returns an array of objects fyi)
I need key to actually be the string from this.attr('name').
Whats the best way to assign a string as a key in Javascript, considering what I'm trying to do?
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);
}
You can't define an object literal with a dynamic key. Do this :
var o = {};
o[key] = value;
return o;
There's no shortcut (edit: there's one now, with ES6, see the other answer).