This question already has answers here:
What do square brackets around a property name in an object literal mean?
(2 answers)
Closed 7 years ago.
Look at the example here:
https://github.com/rackt/redux/blob/master/examples/real-world/actions/index.js
return {
[CALL_API]: {
types: [ USER_REQUEST, USER_SUCCESS, USER_FAILURE ],
endpoint: `users/${login}`,
schema: Schemas.USER
}
}
CALL_API is in square brackets so I assumed maybe it was an array and this was a destructuring thing.
But CALL_API is defined as
export const CALL_API = Symbol('Call API')
So it's not an array or anything. I've also seen the use of square braces with non-symbols. So what's the difference between
CALL_API: {}
and
[CALL_API]: {}
This is a computed property - it's the equivalent of:
let result = {}
result[CALL_API] = { ... };
return result;
Combining this with Symbol lets the library author create a protocol that will not collide with other protocols (e. g. if the protocol was a string "call" then it could collide with other libraries that use someObject.call for their (unrelated) protocols - as well as colliding with Function.prototype.call.)
What this is doing is taking the value of the express [CALL_API] and using it as the key, thus setting the key dynamically.
Example:
var x = "hello";
var y = {
[x]: "world"
};
console.log(y); // Object {hello: "world"}
After some testing, I recommend being very careful with this. The following is perfectly valid:
var x = {"will": "this work?"};
var y = {[x]: "let's see"};
console.log(y); // Object {[object Object]: "let's see"}
console.log(y['[object Object]']); // "let's see"
Related
This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
Closed 5 months ago.
const lookup = {
alpha : 'Adams',
bravo : 'Boston',
charlie : 'Chicago',
delta : 'Denver',
echo : 'Easy',
foxtrot : 'Frank'
}
result = lookup[val];
im confused as to why i am able to do lookup[val] but lookup.val would not work here.
or something like
const testObj = {
12: "Namath",
16: "Montana",
19: "Unitas"
};
const playerNumber = 16;
const player = testObj[playerNumber];
testObj[playerNumber] would work but testObj.playerNumber would not. i initally assumed because 12,16,19 were int but even changing them to strings would be the same result where dot notation dont work but bracket will.
when storing an objects property into a var are we only allowed to use bracket? is so, how come if i was to do console.log(testObj.playerNumber) would not work but console.log(testObj[playerNumber]) will?
By doing testObj.playerNumber you are not invoking the variable playerNumber, but rather accessing a playerNumber property within the testObj object.
Something like this:
const testObj = {
playerNumber: "12"
};
testObj.playerNumber // 12
This question already has answers here:
Convert a JavaScript string in dot notation into an object reference
(34 answers)
Closed 5 years ago.
I have this code :
success(JSON.parse(xhr.responseText).items[0].snippet.title);
The problem is I can access what I want with this but I'd like to be able to do this :
var path = 'items[0].snippet.title';
success(JSON.parse(xhr.responseText).path);
And it doesn't work :(
It's probably nothing but I can't figure out why.
Thanks!
For accessing object properties by string you need to use [ ] notation:
var foo = {bar : 2};
foo['bar']; // 2
But that won't work for nested properties, here is the approach I would follow using Array.reduce and ES6:
let path = 'items.snippet.title';
let response = JSON.parse(xhr.responseText);
let result = path.split('.').reduce((pre,cur) => {
return pre[cur];
}, response);
success(result);
In the first iterarion pre will be response, and cur 'items' returning result.items and so on, it won't work when accesing array indexes though so you will need to add some extra logic inside the reduce function.
const [, cur, position] = cur.match(/^([^\[]+)(?:\[(\d+)])?$/);
// filter foo[1] capturing foo and 1, then assign them using destructuring.
// Thanks for edit!
return ( Array.isArray(pre[cur]) ? pre[cur][position] : pre[cur]);
This question already has answers here:
Difference between ES6 object method assignment: a, 'a', and ['a']?
(2 answers)
Closed 6 years ago.
I've found some wild code on the web i don't understand:
return Object.assign({}, state, {
[action.subreddit]: posts(state[action.subreddit], action)
})
What is [action.subreddit] doing? I thought that object keys had to be strings but this appears to be an array?
I'm hoping to understand mechanically how this code works.
thank you!
That's not an array as key, it's the es6 way to use a variable (/ a computed property) as the key.
Consider this:
var a = "foo";
function getKey() {
return "myKey";
}
var obj = {
[a] : "bar",
[getKey()] : "baz"
};
console.log(obj.foo); // bar
console.log(obj.myKey) // baz
So [action.subreddit] just sets the key's name to whatever value action.subreddit is holding.
This question already has answers here:
How does this object method definition work without the "function" keyword?
(2 answers)
Closed 6 years ago.
Accidentally I written a code like below,
var x = {hai:10,test(){ alert("I am alive")}};
x.test(); //alerting the value
It is working fine and I wonder how this code is working? since it was considered previously as an invalid grammar. And I know, In ECMAscript 6, there is a shorthand for assigning properties has been introduced.
Example:
var x = 5, y = {x}; // is as same as var x=5,y={x:x};
But I am not sure about the function definition. Can anyone explain about it with proof from documentation?
This is a Feature coming with ES2015. You can skip the function-keyword for method-definitions (not for plain functions).
So { doSth(){/*...*/ } } is simply a shorthand for { doSth: function(){/*...*/ } }
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Method_definitions
MDN
Starting with ECMAScript 2015 (ES6), a shorter syntax for method
definitions on objects initializers is introduced. It is a shorthand
for a function assigned to the method's name.
Syntax
var obj = {
property( parameters… ) {},
*generator( parameters… ) {},
// also with computed keys:
[property]( parameters… ) {},
*[generator]( parameters… ) {},
// compare ES5 getter/setter syntax:
get property() {},
set property(value) {}
};
You are now able to shorten this to:
var obj = {
foo() {},
bar() {}
};
MDN Links to ECMA
Enhanced Object Literals
Object literals are extended to support setting the prototype at
construction, shorthand for foo: foo assignments, defining methods,
making super calls, and computing property names with expressions.
Together, these also bring object literals and class declarations
closer together, and let object-based design benefit from some of the
same conveniences.
var obj = {
// __proto__
__proto__: theProtoObj,
// Shorthand for ‘handler: handler’
handler,
// Methods
toString() {
// Super calls
return "d " + super.toString();
},
// Computed (dynamic) property names
[ 'prop_' + (() => 42)() ]: 42
};
Reference : https://github.com/lukehoban/es6features#enhanced-object-literals
This question already has answers here:
What do curly braces in JavaScript mean?
(10 answers)
Closed 9 years ago.
I'm looking over this code:
$(function(){
var $sidescroll = (function() {
init = function() {
//STUFF
};
return { init : init }; //What does this do?
})();
$sidescroll.init();
});
What does the return statement mean? I haven't seen curly braces in a return statement before, and am not even sure what 'init : init' does.
Curly braces mean two things in javascript:
blocks
object literals
You've probably seen the second -- also known in other languages as "dictionaries", key-value pairs, associative arrays, etc:
myDict = { a: "apple", b: "banana" };
When we say
return { a: "apple" };
it is the same as saying
myDict = { a: "apple" };
return myDict;
The "confusing" thing in this case is that (1) the key and the value are identical/have the same character representation, and (2) the value is not a normal string or variable but, a function. That is, accessing the key "init" of your object/dictionary will give you a function that you can call with ().
It returns a new Object instance with the init field set to the value of the init variable. This is called an "Object literal"
I.e.
return { init : init };
is the same as
var o = new Object();
o.init = init;
return o;