JAVASCRIPT: Push object to array [duplicate] - javascript

I'm trying to create a dictionary object like so
var obj = { varName : varValue };
What I'm expecting is if varName='foo', the obj should be {'foo', 'some value' } however what I see is {varName, 'some value'} the value of variable is not being used but a variable name as a key. How do I make it so that varible value is used as key?

Try like this:
var obj = {};
obj[varName] = varValue;
You can't initialize objects with 'dynamic' keys in old Javascript. var obj = { varName : varValue }; is equivalent to var obj = { "varName" : varValue };. This is how Javascript interprets.
However new ECMAScript supports computed property names, and you can do:
var obj = { [varName]: varValue };

Starting with ECMAScript 2015, which has gotten better browser support in the last year(s), you can use the variable index notation:
const obj = { [varName] : varValue };
This is syntactically the same as
var obj = {};
obj[varName] = varValue;
You can also use expressions or Symbols as property key:
const contact = {
company: companyName,
};
const companiesWithContacts = {
[contact.company.toLowerCase()]: true
};
const myList = {
[Symbol.iterator]: createIteratorForList
};
function createIteratorForList() { ... }

Related

Unusual syntax to create object method from a single item string array

I come cross this redux-actions tutorial, and I noticed a unusual syntax to create an object method:
const stringArray = ["STRING_ARRAY"];
const strangeObject = {
[stringArray]() {
console.log(stringArray);
}
};
Can someone name or explain the syntax feature in use?
It's a mix of two features of ES6.
You can have computed property in an object:
const b = "foo";
const a = {
[b]: true
};
// same as
const a = {};
a[b] = true;
There is also a shorthand for functions:
const a = {
b() { console.log("foo");}
};
// same as
const a = {
b: function() { console.log("foo");}
};
If you mix the two, you get what you have: a method whose name is a computed value. Here your object will be the same as
const strangeObject = {
STRING_ARRAY: function() {
console.log("STRING_ARRAY");
}
};
Whenever a computed value for an object is not a string, as in your case, it will be converted to a string.
In your case
["STRING_ARRAY"].toString() === "STRING_ARRAY"
so it does not change much.

Real use case dynamic (computed) property

A dynamic property:
var obj = {
// Computed (dynamic) property names
[ 'prop_' + (() => 42)() ]: 42
};
This is of course very fancy. But where could someone use this without adding unnecessary complexity?
If you have a property name as a constant:
var obj = { [SOME_CONSTANT]: 42 };
One case where I wanted it was where property names for JSON were defined in generated files, based off Java classes.
// Generated
var SomeJsonBodyParams = {NAME: 'name', ID: 'id', ETA, 'estimatedTimeOfArrival'};
// Using it
sendAjax('some/url', {
[SomeJsonBodyParams.NAME] = userData.name,
...
});
We even had a method so we could kind of do it
function makeObj() {
var obj = {};
for (var i=0; i < arguments.length; i+=2) {
obj[i] = obj[i+i];
}
return obj;
}
sendAjax('some/url', makeObj(
SomeJsonBodyParams.NAME, userData.name,
...
));
You can use it in class and with Symbols:
class MyClass {
[Symbol.iterator]() {
// my iterator
}
}
Let's say you have:
var hi = 'hi';
var test = 'test';
var hello = 'hello';
Instead of:
var object = {};
object[hi] = 111;
object[test] = 222;
object[hello] = 333;
You could write it in a much shorter syntax:
var object = {
[hi]: 111,
[test]: 222,
[hello]: 333
}
E.g. it could be used when you want to use a, let's say, constant as a key in object.
const DATA_TYPE = {
PERSON: 'person',
COMPANY: 'company'
};
let cache = {
[DATA_TYPE.PERSON]: getPerson()
};
And later access:
cache[DATA_TYPE.PERSON]
Instead of DATA_TYPE.PERSON could be anything (including some real-time calculated values).

JS - Create object shorthand

Take the below object:
var value = 'bar';
var obj = { foo: value }
// -> Object { foo="bar" }
Supposing the key was also a variable, one could go:
var key = 'foo', value = 'bar';
var obj = {}
obj[key] = value;
// -> Object { foo="bar" }
Now, I want to do this in one line (shorthand). So I tried:
var obj = {}[key] = value; // or,
var obj = ({})[key] = value; // or,
var obj = new Object()[key] = value;
// -> "bar"
This oddly produces a String instead of an Object.
Is there any way to do this shorthand?
ECMAScript 6 will allow you to do
var obj = {
[key]: value
};
Browser support is not great yet, but transpilers such as 6to5 allow you to use this notation today!
You can, or almost can. If you put the creation of the object, and its assignment to obj in parentheses, you can set a property of the result of that expression:
var obj, key='foo', value = 'bar';
(obj = {})[key] = value;
alert(obj); // [object Object]
alert(obj.foo); // bar
The var keyword cannot be included in that expression within parentheses, so either you will have to declare obj before (like I did), or not declare it at all and accept that it will be in global scope.
Depends on what you call a one-liner, with some code golf you can do
var obj = (function(o) {o[key]=value; return o})({});
it think that's the shortest you'll get it ?
Something like that is coming in ECMAScript 6:
With ECMAScript 6, there is a shorter notation available to achieve
the same:
var a = "foo",
b = 42,
c = {};
// Shorthand property names (ES6)
var o = { a, b, c };
So you could create your object with the following code
var foo = 'bar';
var obj = {foo};
No shorthand in ECMAScript 5 (the current version), but you can make a method
function createObject(key, value /*, key, value, ... */ ) {
var object = {};
for (var i = 0; i < arguments.length; i = i + 2) {
object[arguments[i]] = arguments[i+1];
}
return object;
}
Then you can call it like this
var obj = createObject(key, value, 'anotherKey', 'anotherVal');

In JS, how to declare a value for an object and have all parent keys automatically be created?

myObject = {};
myObject.property1 = "123"
Typing myObject.property1 returns 123
mySecondObject = {};
mySecondObject.property1.value.type.price = "456"
returns TypeError: Cannot set property 'value1' of undefined because all or some parent keys haven't been defined yet, so you have to do something like:
mySecondObject = {};
mySecondObject.property1 = {};
mySecondObject.property1.value = {};
mySecondObject.property1.value.type = {};
mySecondObject.property1.value.type.price = "456"
Is there a method in JS that allows you to just declare an object with as many keys as you want and automatically creates all the parent keys? I couldn't find anything in Underscore.
There's no (standard) function for doing this.
An alternate initialiser is this:
var mySecondObject = { property1: { value: { type: { price : "456" } } } };

Concatenate object field with variable in javascript

I'm building an object in javascript to store data dynamically.
Here is my code :
var id=0;
function(pName, pPrice) {
var name = pName;
var price = pPrice;
var myObj = {
id:{
'name':name,
'price':price
},
};
(id++); //
console.log(myObj.id.name); // Acessing specific data
}
I want my id field to be defined by the id variable value so it would create a new field each time my function is called. But I don't find any solution to concatenate both.
Thanks
You can create and access dynamicly named fields using the square bracket syntax:
var myObj = {};
myObj['id_'+id] = {
'name':name,
'price':price
}
Is this what you want ?
var myObj = {};
myObj[id] = {
'name':name,
'price':price
};
console.log(myObj[id]name); // Acessing specific data
You can use [] to define the dynamic property for particular object(myObj), something like
var myObj = {};
myObj[id] = {'nom':nom, 'prix':prix};
Example
function userDetail(id, nom, prix) {
var myObj = {};
myObj[id] = {'nom':nom, 'prix':prix};
return myObj;
}
var objA = userDetail('id1', 'sam', 2000);
var objB = userDetail('id2', 'ram', 12000);
var objC = userDetail('id3', 'honk', 22000);
console.log(objA.id1.nom); // prints sam
console.log(objB.id2.nom); // prints ram
console.log(objC.id3.prix);// prints 22000
[DEMO]

Categories

Resources