Short for of creating an object from 2 variables [duplicate] - javascript

This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 6 years ago.
Is there a short form of doing such operation:
function doObject(key, value){
let object = {};
return object[key] = value;
}
UPD: forget about function, I use it just to isolate scope and provide to params key and value. I don't need to implement the function but logic that it does

const doObject = (key, value) => ({[key]: value});
// ^^^^^^^^^^^^ ^ ^^^^^
// 1 2 3
Arrow function syntax
Wrapping with braces allows you to return an object literal without the extended syntax. (Otherwise, it thinks the {} are the block delimiters.
Computed object literal property key.

You can use a computed property name for the object:
function doObject(key, value){
return {
[key]: value
};
}

Related

Defining an object with a dynamic key in node js (javascript) [duplicate]

This question already has answers here:
How To Set A JS object property name from a variable
(8 answers)
Closed 4 years ago.
I need to do this :
let obj = {}
obj.obj1 = {'obj11':5}
console.log(obj.obj1.obj11)
//5
but I need to define the last key of the last object dynamically for example, something like this:
let obj = {}
key = 'obj11'
obj.obj1 = { key :5}
console.log(obj.obj1.obj11)
// undefined
Try
obj.obj1[key] = 5;
console.log(obj.obj1.obj11);
The object notation syntax does not support variables as keys directly, but java-script dictionaries do.
To evaluate the variable in the object notation syntax, use a bracket like so
obj.obj1 = {[key]: 5};
console.log(obj.obj1.obj11);
To define computed properties in javascript objects use [].
Try the following:
let obj = {}
key = 'obj11'
obj.obj1 = { [key] :5}
console.log(obj.obj1.obj11)
For reference : Reference
You'll have to use bracket notation for this like
let obj = {}
key = 'obj11'
obj.obj1 = { [key] :5}
console.log(obj.obj1.obj11)
Yes, you can do this:
console.log(obj.obj1[key]);
Every object in JavaScript is basically a dictionary so you can access it via the dictionary syntax.

Can the Object literal take values other than key value pair? [duplicate]

This question already has answers here:
Getters \ setters for dummies
(14 answers)
Closed 5 years ago.
my so far understanding with object literal is we can use it like the key value pair, where key is the property and the value can be a actual value, a function or a anonymous function
function a() {
return 'value b';
}
var result = {
'keya': 'valueA',
'keyb': a,
'keyc': function () {
console.log('some value');
}
};
till i read this block of code
var obj = {
log: ['test'],
get latest() {
if (this.log.length == 0) return undefined;
return this.log[this.log.length - 1];
}
}
console.log(obj.latest); // Will return "test".
my question is, in the above code the function latest() doesnt have any key then how can it be used inside a object literal, am i missing something
This is ES6 (which is also called ES2015) syntax, it's a newer version of Javascript that lets you do this.
You would've had to have the key there in ES5 code.

How to access sub-values of a multi-dimensional object [duplicate]

This question already has answers here:
Convert a JavaScript string in dot notation into an object reference
(34 answers)
Closed 7 years ago.
is it possible to get a reference to an object with the object itself
obj
and the attributes in string form
'address.town.street'
so that at the end it resolves
obj.address.town.street
i could immageine smth like the eval() function.
Try
function getValue(obj, path) {
return path.split(".").reduce(function(obj, name){ return obj[name]}, obj);
}
Do not use eval. Use this instead
Object.prototype.nestedByString=function(reference){
var current=this;
path=reference.split(".");
for(var i=0;i<path.length;i++){
current=current[path[i]];
}
return current;
}
Here is a demo
I suppose that if you're allergic to extending native prototypes, you can do this
function nestedByString(obj,reference){
var current=obj;
path=reference.split(".");
for(var i=0;i<path.length;i++){
current=current[path[i]];
}
return current;
}

jQuery expression as object key [duplicate]

This question already has answers here:
How to create an object property from a variable value in JavaScript? [duplicate]
(9 answers)
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 8 years ago.
I need to figure out how to create a dynamic key string for an object. This expression makes JavaScript complain.
return {$(this).val(): true}; // returns an object e.g. {2: true}
What am I doing wrong?
You have to create the object, then use bracket notation for the dynamic key
var obj = {};
var val = $(this).val();
obj[val] = true;
return obj;
or a completely unnecessary one-liner
return (function(o,e) {o[e.value]=true; return o;})({}, this);
The JavaScript object literal syntax {x: y} specifies that x will be a (possibly) quoteless string, and y any value. You can't use this syntax for dynamic keys.
Use this instead:
var foo = {};
foo[$(this).val()] = true;
return foo;

Javascript variable object keys [duplicate]

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.
I am attempting to add a variable key, with no luck.
Here's what I got so far:
mysql('translations',{
check: 'element_id',
element_id: element_id,
{'lang-'+lang_id}: value
});
The variable key is the last line of the function.
Any ideas?
You can't use expressions for the identifiers in an object literal.
First create the object, then you can use dynamic names:
var obj = {
check: 'element_id',
element_id: element_id,
}
obj['lang-'+lang_id] = value;
mysql('translations', obj);
You can do this:
var x = {
check: 'element_id',
element_id: element_id
};
x['lang-'+lang_id] = value;
mysql('translations', x);

Categories