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).
Related
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"}
Given an object like this:
var obj = {
"name":"JonDoe",
"gender":"1",
"address":{
"phone":"1"
}
}
I know you can have such things :
console.log(obj['name']); // returns 'JonDoe'
My problem comes with the inner structure 'address', whose 'phone' inner field I would like to target with obj['address.phone'] but it returns instead undefined where all level 1 field return the matching value.
I am quite sure you could do it with some (de)serialisation function or any json lib, but I am am wondering if there's a smart way to list all inner structures like 'address' with no preliminary knowledge of which field I am going to target (like obj[field]).
Do:
var phone = obj.address.phone;
Bracket notation is typically used when using variables as the property name. If you know the properties, feel free to use dot notation (seen above)
You can try this:
var addresses = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
addresses.push(obj[key]['address']);
}
}
console.log(addresses);
For more complex object property querying use this library linq.js - LINQ for JavaScript
Update
If you want to list all address phones no matter how deep they are try recursive scanning:
var phones = [];
var scan = function(obj) {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
if (key == 'address') {
phones.push(obj[key]['phone']);
}
else if (typeof obj[key] === 'object') {
scan(obj[key]);
}
}
}
};
scan(obj)
console.log(phones);
This question already has answers here:
Add a property to a JavaScript object using a variable as the name? [duplicate]
(14 answers)
Variable as the property name in a JavaScript object literal? [duplicate]
(3 answers)
Closed 8 years ago.
Say I call following function:
var query = makeQuery("email", "foo#bar.com");
The implementation I have is:
makeQuery = function (key, value) {
return { key: value};
}
The object I end up with is: {"key": "foo#bar.com"}, which is obviously wrong. I would like to obtain {"email": "foo#bar.com"} instead. I tried setting it like so:
makeQuery = function (key, value) {
return { JSON.stringify(key): value};
}
... but I get a "SyntaxError: Unexpected token ." I've also thought of using toString() and even eval(), without success. So my problem is to be able to set the property of the object returned in makeQuery() using its real value, that is, pick up the value of 'key', not setting the property with the 'key' literal.
Thanks for the help.
Create the object first and then use the square bracket syntax so you can set the property using the value of key:
makeQuery = function (key, value) {
var query = {};
query[key] = value;
return query;
};
For variable keys in objects, use
var obj[key] = value
So then it becomes:
function makeQuery(key, value) {
var obj = {};
obj[key] = value;
return obj;
}
define an object..
makeQuery = function (key, value) {
var o = {};
o[key] = value;
return o;
}
This question already has answers here:
JavaScript hashmap equivalent
(17 answers)
Closed 6 years ago.
How can you create the JavaScript/JQuery equivalent of this Java code:
Map map = new HashMap(); //Doesn't not have to be a hash map, any key/value map is fine
map.put(myKey1, myObj1);
map.put(myKey2, myObj2); //Repeat n times
function Object get(k) {
return map.get(k);
}
Edit: Out of date answer, ECMAScript 2015 (ES6) standard javascript has a Map implementation, read here for more info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
var map = new Object(); // or var map = {};
map[myKey1] = myObj1;
map[myKey2] = myObj2;
function get(k) {
return map[k];
}
//map[myKey1] == get(myKey1);
Just use plain objects:
var map = { key1: "value1", key2: "value2" }
function get(k){
return map[k];
}
function Map() {
this.keys = new Array();
this.data = new Object();
this.put = function (key, value) {
if (this.data[key] == null) {
this.keys.push(key);
}
this.data[key] = value;
};
this.get = function (key) {
return this.data[key];
};
this.remove = function (key) {
this.keys.remove(key);
this.data[key] = null;
};
this.each = function (fn) {
if (typeof fn != 'function') {
return;
}
var len = this.keys.length;
for (var i = 0; i < len; i++) {
var k = this.keys[i];
fn(k, this.data[k], i);
}
};
this.entrys = function () {
var len = this.keys.length;
var entrys = new Array(len);
for (var i = 0; i < len; i++) {
entrys[i] = {
key: this.keys[i],
value: this.data[i]
};
}
return entrys;
};
this.isEmpty = function () {
return this.keys.length == 0;
};
this.size = function () {
return this.keys.length;
};
}
This is an old question, but because the existing answers could be very dangerous, I wanted to leave this answer for future folks who might stumble in here...
The answers based on using an Object as a HashMap are broken and can cause extremely nasty consequences if you use anything other than a String as the key. The problem is that Object properties are coerced to Strings using the .toString method. This can lead to the following nastiness:
function MyObject(name) {
this.name = name;
};
var key1 = new MyObject("one");
var key2 = new MyObject("two");
var map = {};
map[key1] = 1;
map[key2] = 2;
If you were expecting that Object would behave in the same way as a Java Map here, you would be rather miffed to discover that map only contains one entry with the String key [object Object]:
> JSON.stringify(map);
{"[object Object]": 2}
This is clearly not a replacement for Java's HashMap. Bizarrely, given it's age, Javascript does not currently have a general purpose map object. There is hope on the horizon, though: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map although a glance at the Browser Compatability table there will show that this isn't ready to used in general purpose web apps yet.
In the meantime, the best you can do is:
Deliberately use Strings as keys. I.e. use explicit strings as keys rather than relying on the implicit .toString-ing of the keys you use.
Ensure that the objects you are using as keys have a well-defined .toString() method that suits your understanding of uniqueness for these objects.
If you cannot/don't want to change the .toString of the key Objects, when storing and retrieving the entries, convert the objects to a string which represents your understanding of uniqueness. E.g. map[toUniqueString(key1)] = 1
Sometimes, though, that is not possible. If you want to map data based on, for example File objects, there is no reliable way to do this because the attributes that the File object exposes are not enough to ensure its uniqueness. (You may have two File objects that represent different files on disk, but there is no way to distinguish between them in JS in the browser). In these cases, unfortunately, all that you can do is refactor your code to eliminate the need for storing these in a may; perhaps, by using an array instead and referencing them exclusively by index.
var map = {'myKey1':myObj1, 'mykey2':myObj2};
// You don't need any get function, just use
map['mykey1']
If you're not restricted to JQuery, you can use the prototype.js framework. It has a class called Hash: You can even use JQuery & prototype.js together. Just type jQuery.noConflict();
var h = new Hash();
h.set("key", "value");
h.get("key");
h.keys(); // returns an array of keys
h.values(); // returns an array of values
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.
Is it at all possible to use variable names in object literal properties for object creation?
Example
function createJSON (propertyName){
return { propertyName : "Value"};
}
var myObject = createJSON("myProperty");
console.log(myObject.propertyName); // Prints "value"
console.log(myObject.myProperty); // This property does not exist
If you want to use a variable for a property name, you can use Computed Property Names. Place the variable name between square brackets:
var foo = "bar";
var ob = { [foo]: "something" }; // ob.bar === "something"
If you want Internet Explorer support you will need to use the ES5 approach (which you could get by writing modern syntax (as above) and then applying Babel):
Create the object first, and then add the property using square bracket notation.
var foo = "bar";
var ob = {};
ob[foo] = "something"; // === ob.bar = "something"
If you wanted to programatically create JSON, you would have to serialize the object to a string conforming to the JSON format. e.g. with the JSON.stringify method.
ES6 introduces computed property names, which allow you to do
function CreateJSON (propertyName){
var myObject = { [propertyName] : "Value"};
}
Note browser support is currently negligible.
You can sort of do this:
var myObject = {};
CreateProp("myProperty","MyValue");
function CreateProp(propertyName, propertyValue)
{
myObject[propertyName] = propertyValue;
alert(myObject[propertyName]); // prints "MyValue"
};
I much perfer this syntax myself though:
function jsonObject()
{
};
var myNoteObject = new jsonObject();
function SaveJsonObject()
{
myNoteObject.Control = new jsonObject();
myNoteObject.Control.Field1= "Fred";
myNoteObject.Control.Field2= "Wilma";
myNoteObject.Control.Field3= "Flintstone";
myNoteObject.Control.Id= "1234";
myNoteObject.Other= new jsonObject();
myNoteObject.Other.One="myone";
};
Then you can use the following:
SaveJsonObject();
var myNoteJSON = JSON.stringify(myNoteObject);
NOTE: This makes use of the json2.js from here:http://www.json.org/js.html
One thing that may be suitable (now that JSON functionality is common to newer browsers, and json2.js is a perfectly valid fallback), is to construct a JSON string and then parse it.
function func(prop, val) {
var jsonStr = '{"'+prop+'":'+val+'}';
return JSON.parse(jsonStr);
}
var testa = func("init", 1);
console.log(testa.init);//1
Just keep in mind, JSON property names need to be enclosed in double quotes.