Square Brackets Javascript Object Key - javascript

Can anyone explain how the why/how the below method of assigning keys in JavaScript works?
a = "b"
c = {[a]: "d"}
return:
Object {b: "d"}

It's the new ES2015 (the EcmaScript spec formally known as ES6) computed property name syntax. It's a shorthand for the someObject[someKey] assignment that you know from ES3/5:
var a = "b"
var c = {[a]: "d"}
is syntactic sugar for:
var a = "b"
var c = {}
c[a] = "d"

Really the use of [] gives an excellent way to use actual value of variable as key/property while creating JavaScript objects.
I'm pretty much statisfied with the above answer and I appreciate it as it allowed me to write this with a little example.
I've executed the code line by line on Node REPL (Node shell).
> var key = "fullName"; // Assignment
undefined
>
> var obj = {key: "Rishikesh Agrawani"} // Here key's value will not be used
undefined
> obj // Inappropriate, which we don't want
{ key: 'Rishikesh Agrawani' }
>
> // Let's fix
undefined
> var obj2 = {[key]: "Rishikesh Agrawani"}
undefined
> obj2
{ fullName: 'Rishikesh Agrawani' }
>

const animalSounds = {cat: 'meow', dog: 'bark'};
const animal = 'lion';
const sound = 'roar';
{...animalSounds, [animal]: sound};
The result will be
{cat: 'meow', dog: 'bark', lion: 'roar'};

Also, only condition to use [] notation for accessing or assigning stuff in objects when we don't yet know what it's going to be until evaluation or runtime.

I want to make an object but I don't know the name of the key until runtime.
Back in the ES5 days:
var myObject = {};
myObject[key] = "bar";
Writing two lines of code is so painful... Ah, ES6 just came along:
var myObject = {[key]:"bar"};
If the value of key equals foo, then both approaches result in:
{foo : "bar"}

Related

Index a JS object like a Metatable in Lua

Is there a way to index an object in JavaScript like a Metatable in Lua?
Like for example:
var obj = {a:"a",b:"b",properties:{c:"c",d:"d"}}
metatable(obj,obj.properties) // Make it so that if you try to index something that's not inside the object it will go to the parameter one
console.log(obj.a) // "a"
console.log(obj.c) // "c"
To LMD:
How do I do it for multiple objects? Like for example:
var objs = [
obj1 = {name:"Button";class:"button";properties:{text:"Press this"}]
]
for (i in objs){
metatable(objs[i],objs[i].properties)
}
console.log(objs.obj1.text) // "Press this"
Yes: JavaScript has prototypes. These aren't exactly the same as Lua but can be used for simple metatable indexing purposes. One way to achieve your example would be as follows:
const properties = {c: "c", d: "d"} // prototype
const obj = Object.create(properties) // create object with prototype
obj.a = "a"; obj.b = "b";
console.log(obj.a) // "a"
console.log(obj.c) // "c"
Or if you already have the objects given, as in your second example, you may want to use Object.setPrototypeOf(object, prototype), which is comparable to setmetatable(object, {__index = prototype}) in Lua:
const objs = [{name:"Button", class:"button", properties: {text:"Press this"}}]
for (const obj of objs) Object.setPrototypeOf(obj, obj.properties)
console.log(objs[0].text) // "Press this"
that is, the metatable function you've been searching for literally is Object.setPrototypeOf!

Square bracket syntax for method definition on an object [duplicate]

Can anyone explain how the why/how the below method of assigning keys in JavaScript works?
a = "b"
c = {[a]: "d"}
return:
Object {b: "d"}
It's the new ES2015 (the EcmaScript spec formally known as ES6) computed property name syntax. It's a shorthand for the someObject[someKey] assignment that you know from ES3/5:
var a = "b"
var c = {[a]: "d"}
is syntactic sugar for:
var a = "b"
var c = {}
c[a] = "d"
Really the use of [] gives an excellent way to use actual value of variable as key/property while creating JavaScript objects.
I'm pretty much statisfied with the above answer and I appreciate it as it allowed me to write this with a little example.
I've executed the code line by line on Node REPL (Node shell).
> var key = "fullName"; // Assignment
undefined
>
> var obj = {key: "Rishikesh Agrawani"} // Here key's value will not be used
undefined
> obj // Inappropriate, which we don't want
{ key: 'Rishikesh Agrawani' }
>
> // Let's fix
undefined
> var obj2 = {[key]: "Rishikesh Agrawani"}
undefined
> obj2
{ fullName: 'Rishikesh Agrawani' }
>
const animalSounds = {cat: 'meow', dog: 'bark'};
const animal = 'lion';
const sound = 'roar';
{...animalSounds, [animal]: sound};
The result will be
{cat: 'meow', dog: 'bark', lion: 'roar'};
Also, only condition to use [] notation for accessing or assigning stuff in objects when we don't yet know what it's going to be until evaluation or runtime.
I want to make an object but I don't know the name of the key until runtime.
Back in the ES5 days:
var myObject = {};
myObject[key] = "bar";
Writing two lines of code is so painful... Ah, ES6 just came along:
var myObject = {[key]:"bar"};
If the value of key equals foo, then both approaches result in:
{foo : "bar"}

How to make each key of an object as a variable with the same name as the key in Javascript?

I have a javascript object like this:
var obj1={a:1,b:2,c:3}
From this i need to extract each key as a variable like this:
var a=1
var b=2
var c=3
How can this be done?
It can be done using ES6 destructuring, you can explode all the object's properties and assign it in a variable the same as the property's name
var {a,b,c} = obj1;
console.log(a);
console.log(b);
console.log(c);
It's not a great looking solution (this isn't the sort of thing you should be doing - better to work with just the initial object), but you could assign all properties of obj1 to the window object, allowing you to reference them standalone, without having to know the keys beforehand:
var obj1 = {
a: 1,
b: 2,
c: 3
};
Object.assign(window, obj1);
console.log(c);
Try with:
var obj1={a:1,b:2,c:3}
let keys = Object.keys(obj1)
keys.forEach(key => {
let value = obj1[key.toString()];
console.log(key); // Use Key
console.log(value) // Use Value
})

What does a javascript symbol in brackets as an object key mean? [duplicate]

Can anyone explain how the why/how the below method of assigning keys in JavaScript works?
a = "b"
c = {[a]: "d"}
return:
Object {b: "d"}
It's the new ES2015 (the EcmaScript spec formally known as ES6) computed property name syntax. It's a shorthand for the someObject[someKey] assignment that you know from ES3/5:
var a = "b"
var c = {[a]: "d"}
is syntactic sugar for:
var a = "b"
var c = {}
c[a] = "d"
Really the use of [] gives an excellent way to use actual value of variable as key/property while creating JavaScript objects.
I'm pretty much statisfied with the above answer and I appreciate it as it allowed me to write this with a little example.
I've executed the code line by line on Node REPL (Node shell).
> var key = "fullName"; // Assignment
undefined
>
> var obj = {key: "Rishikesh Agrawani"} // Here key's value will not be used
undefined
> obj // Inappropriate, which we don't want
{ key: 'Rishikesh Agrawani' }
>
> // Let's fix
undefined
> var obj2 = {[key]: "Rishikesh Agrawani"}
undefined
> obj2
{ fullName: 'Rishikesh Agrawani' }
>
const animalSounds = {cat: 'meow', dog: 'bark'};
const animal = 'lion';
const sound = 'roar';
{...animalSounds, [animal]: sound};
The result will be
{cat: 'meow', dog: 'bark', lion: 'roar'};
Also, only condition to use [] notation for accessing or assigning stuff in objects when we don't yet know what it's going to be until evaluation or runtime.
I want to make an object but I don't know the name of the key until runtime.
Back in the ES5 days:
var myObject = {};
myObject[key] = "bar";
Writing two lines of code is so painful... Ah, ES6 just came along:
var myObject = {[key]:"bar"};
If the value of key equals foo, then both approaches result in:
{foo : "bar"}

Is it possible to define a dynamically named property using object literal in JavaScript? [duplicate]

This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 1 year ago.
Consider the following
var a = {foo: "bar"};
Equivalent to
var a = {};
a.foo = "bar";
Equivalent to
var a = {};
a['foo'] = "bar";
Equivalent to
var a = {}
var b = "foo";
a[b] = "bar";
Is it possible to do something like
var b = "foo";
var a = { [b]: "bar" };
Such that the result would be
// => {foo: "bar"}
Acceptable solutions are in JavaScript or CoffeeScript
No.
There is no way to do it using object literal notation.
UPDATE: According to the ECMAScript standard 6.0 you are now able to do the following:
var b = 'foo';
var a = { [b]: 'bar' };
console.log( a.foo ); // "bar"
However, this solution won't work in old browsers, which do not support ES6.
ES6 supports computed properties.
// code from my original question now works in ES6 !
let b = "foo";
let a = { [b]: "bar" };
a.foo; //=> "bar"
Any expression can be used within the [] to define the property name
let a = {
[(xs => xs.join(''))(['f','o','o'])]: 'bar'
};
a.foo; //=> "bar"
If you need to rely on this behavior in an ES5 world, you can lean on the very capable babel.js to transpile your ES6 code to ES5-compatible code.
JSON parse allows you to convert a JSON string into an object:
JSON.parse('{"'+dynamicProperty+'":"bar"}');
This is not exactly an object litteral, but if your objective is to enter your property name as a variable it works.
As others have said, no, there's currently no syntax for interpolated key strings in object literals in CoffeeScript; but it seems at some point this feature existed! In these GitHub issues there's some discussion about it: #786 and #1731.
It's implemented in Coco and LiveScript as:
b = 'foo'
a = {"#{b}": 'baz'}
# Or..
a = {(b): 'bar'}
As of CoffeeScript version 1.9.1 this works:
b = "foo"
a = "#{b}": "bar"
It compiles to:
var a, b, obj;
b = "foo";
a = (
obj = {},
obj["" + b] = "bar",
obj
);
Try it.
JavaScript
var a, b;
(a = {})[b = 'foo'] = 'bar';
CoffeeScript
(a = {})[b = 'foo'] = 'bar'
To answer your question, this is the only way that I know of. It uses eval. But beware, eval is evil!
var b = "foo";
var a = eval('({ ' + b + ': ' + '"bar"' + ' })');
This is an ugly solution. To play it safe you should not rely on this. Don't use it!

Categories

Resources