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
Related
This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 29 days ago.
In JS/typescript, lets say I have an object like this
var obj = {
a: {
b:{
c:1
}
}
}
And I have a string "b.c". How can I evaluate this using only those variables and get the value 1 from the object without using hacks like eval since typescript would complain.
Thanks
It I understood you question, the keys are known, if so you can use the '[]' to access it :
const a = b.c
is the same thing as
const a = b['c']
but in the second case you can of course use a variable.
Applying this to your object, it would look something like this :
const obj = {
a: {
b: {
c: 1
}
}
}
const outerKey = 'a'
const middleKey = 'b'
const innerKey = 'c'
const value = obj[outerKey][middleKey][innerKey]
console.log(value)
Hope it helped you !
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:
Using integer keys with dot notation to access property in javascript objects
(3 answers)
Closed 6 years ago.
Let's say I have an object:
var elObject = {
one: {
name: "Oliver"}
}
I can access name by doing elObject.one.name and everything is great, but let's say I have this instead:
var elObject = {
1: {
name: "Oliver"}
}
Suddenly, I can't access name through elObject.1.name anymore since I'm using 1 instead of 'one'. Is there a a special escape or something I'm supposed to use with object literal and digits?
You can declare the plain object with number 1 using it as string. Once is not allowed to have a property name starting with number, you can access it using bracket notation.
Example and findle below.
var x = {
'1' : {
name: 'Joao'
}
};
alert(x);
try {
alert(x['1'].name);
}
catch(e){
alert(e.message);
}
https://jsfiddle.net/b4c34wLv/
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"
This question already has an answer here:
How to use the value of a variable in creating an object in JavaScript [duplicate]
(1 answer)
Closed 9 years ago.
saw a few answers related to this, but none answer this version of the subject in question.
Consider the following: (linkto: jsfiddle)
$(function(){
arrKeys = [];
objArr = [];
nameArr = ['name1','name2','name3','name4'];
descArr = ['desc1','desc2','desc3','desc4'];
allValues = {name: nameArr, desc: descArr};
arrKeys[0] = 'name';
arrKeys[1] = 'desc';
first = arrKeys.shift(); // returns 'name'
$(allValues[first]).each(function (key,value) {
console.log(first); //returns 'name'
objArr[key] = {first:value}; //the problem
});
console.log(objArr);
});
With console.log(objArr) producing the following array of objects like so:
[Object, Object, Object, Object]
0: Object
first: "name1"
1: Object
first: "name2"
2: Object
first: "name3"
3: Object
first: "name4"
length: 4
The issue is that I'd like the property "first" to be the value of the var first (which is "name".. So instead, the result would be:
[Object, Object, Object, Object] 0: Object
name: "name1" 1: Object
name: "name2" 2: Object
name: "name3" 3: Object
name: "name4" length: 4
(linkto: jsfiddle)
To set variables as key names you have to use bracket notation;
console.log(first); // returns 'name'
var obj = {};
obj[first] = value;
objArr[key] = obj; // no longer a problem
Sorry it's more verbose :(
Edit;
In ES6 you can now use computed-property-names;
const key = 'name';
const value = 'james';
const obj = {
[key]: value
};
var x = {}
x[first] = value
objArr[key] = x
Javascript object literal syntax treats unquoted keys as if they were quoted strings instead of variable names. You have to use bracket syntax to set properties with names computed at runtime.
(Why are you wrapping your code in a jQuery call? And you really should be using var declarations.)