Get Object element from a variable - javascript

I have an object that i am trying to pull values from according to a certain variable.
Let say i have an object
current = [
goal1 : solve this,
goal2: sleep,]
current.goal1 returns solve this.
but what if i have a variable called task that can be either goal1 or goal2
how can i call current.goal1 by using task variable.
current.task returns undefined.
Is there a way to do that?

You can do something like this.
const current = {
goal1 : "solve this",
goal2: "sleep"};
const task = "goal1";
console.log(current[task]);
This is known as Square brackets property access: object['property']

I hope this helps. Object syntax: between curly braces {}
let current = {
task: {
goal1 : 'solve this',
goal2: 'sleep'
}
};
const { task } = current;
console.log(task)
By using Destructured assignment

Related

JS Symbol as object key

I'm running a node software where in a certain context of the software there is an object which one of it's keys is a Symbol, and it's value is an object. For example:
object = {Symbol(symbol_name): another_object}
I'm trying to get to the 'another_object' keys and values and can't find the way to do so. Suggestions anyone?
The best approach would be to save the Symbol in a variable first, then just use bracket notation to look it up:
const sym = Symbol('symbol_name');
const object = {[sym]: { foo: 'bar' }}
console.log(object[sym]);
If you don't have a reference to the symbol, and the object contains only one symbol, you can get it with getOwnPropertySymbols:
const object = {
[Symbol('symbol_name')]: {
foo: 'bar'
}
};
const sym = Object.getOwnPropertySymbols(object)[0];
console.log(object[sym]);
Put the object key in brackets like this:
object = {[Symbol(symbol_name)]: another_object}

How to set this value as variable?

I want to set the value of this part (shown in imagehere) as a variable?
Just put like var myvariable = data.events, and It should works, If you have any question just comment.
You can do it in several ways:
const data = {event: 'some user event'};
// 1. dot notation
const userEvent1 = data.event;
// 2. Bracket Notation
const key = 'event'
const userEvent2 = data[key]; // or just data['event']
// 3. destructuring
const { event } = data;
console.log('userEvent1:', userEvent1)
console.log('userEvent2:', userEvent2)
console.log('event:', event)
I will attach useful articles:
https://codeburst.io/javascript-quickie-dot-notation-vs-bracket-notation-333641c0f781
https://dmitripavlutin.com/javascript-object-destructuring/
You Can Do It With Pretty Much a lot of ways Like
But the Most Simplest Way is using dot notation
const event = data.event

Objects: Value always undefined

I am working on some keybinding functionality and came across something that is quite confusing to me.
I am doing some regex validation against the user defined keybinding pattern and would then like to assign the pattern as key and value to definedKeys:
const definedPattern = ['a', 'b']
let definedKeys = {}
const bindKeys = () => {
const charKey = (String(definedPattern[0]) + String(definedPattern[1])).match(/^[a-zA-Z]{2}$/)
if (charKey) {
definedKeys[charKey.input[0]] = definedKeys[charKey.input[1]]
}
console.log(definedKeys)
}
bindKeys()
Use definedKeys instead of definedCharKeys as it is not declared neither initailized
Assigning value directly to key instead of refrencing value from definedKeys because value is not still set and it will be always undefined.
definedKeys = {};
const encodeKey = (pKey) => {
charKey = (String(pKey[0]) + String(pKey[1])).match(/^[a-zA-Z]{2}$/);
if (charKey) {
// charKey.input = 'ab'
definedKeys[charKey.input[0]] = charKey.input[1];
}
}
encodeKey('ab');
console.log(definedKeys);
Isn't it because you don't put anything in definedKeys but instead you put it in definedCharKeys?
As per the code. You are not assigning anything in "definedKeys". You are assigning a value in "definedCharKeys" that's why you are getting undefined for the "definedKeys".
Please post full code where are you calling the function so that developers can provide you solution.

why is there comma separator after a method of object?

i am trying to follow a tutorial class building a Game. where i found those mysterious commas. can anyone tell me why should i have to put comma after every methods in an object.
let GameManager = {
setGameStart: function(classType) {
this.resetPlayer(classType);
this.setPreFight();
},
resetPlayer: function(classType) {
switch (classType) {
case "Warrior":
player = new Player(classType, 200, 200, 100, 50);
break;
let getInterface = document.querySelector(".interface");
getInterface.innerHTML = '<div><h3>' + classType + '</h3></div>';
}, setPreFight: function() {
let getHeader = document.querySelector(".header");
getHeader.innerHTML = '<p>Task: Find and enemy!</P>'
},
Because GameManager is an object initializer & according to mdn
an object initializer is a comma-delimited list of zero or more pairs
of property names and associated values of an object, enclosed in
curly braces
let obj = {
prop1: 'someProp',
prop2: 'someProp2',
func1: function() {
console.log(`${this.prop1} ${this.prop2}`)
}
}
obj.func1()
GameManager is similar to the object obj & you call its method by GameManager.setGameStart and so
where i found those mysterious commas. can anyone tell me why should i
have to put comma after every methods in an object.
Ref
No this is not mysterious This is what syntax of object is
You need to seprate key/value pair by comma except the last key/value pair
You are getting confused with creating an object and creating a function. Here, you are creating an object. So the rules of creating objects are to be followed. Each property:value pair must be separated with comma-delimiter. Please note that you can assign function as value of a property as you are doing in the example.
let GameManager = {
//**THIS IS A PROPERTY:VALUE PAIR**
setGameStart: function(classType) {
this.resetPlayer(classType);
this.setPreFight();
},
//**THIS IS ALSO A PROPERTY:VALUE PAIR
someProperty: someValue,
When creating an independent function, you don't do that.
function printSomething(){
console.log("something");
}
function printSomethingElse(){
console.log("somethingElse");
}

create object within object Javascript

My Code :
for( var i in zones) {
var latlons1 = new google.maps.LatLng(zones[i].b.cen_x, zones[i].b.cen_y);
var latlons2 = new google.maps.LatLng(zones[i].b.max_x, zones[i].b.max_y);
var latlons3 = new google.maps.LatLng(zones[i].b.min_x, zones[i].b.min_y);
obj1 = { zones[i].n = {1:latlons1,2:latlons2,3:latlons3} } //here object creation
console.log(obj1);
}
what i am doing wrong? consol log error shows at object create.
When creating an object literal in JavaScript the key and value are separated by a colon (:). Also note that if you want to use dynamic keys then you'll need to use the square bracket notation for setting and accessing those properties. So this:
obj1 = { zones[i].n = {1:latlons1,2:latlons2,3:latlons3} }
should become:
obj1 = {};
obj1[zones[i].n] = {
1: latlons1,
2: latlons2,
3: latlons3
};
If you're confused as to why you have to do it this way it's because the keys aren't evaluated. While you meant that the key should be the value that's referenced by zones[i].n, JavaScript interprets it as the key should be the string literal "zones[i].n", which obviously isn't what you want.
To use an object within an object,
//An object within an object
var NestedObject=new Object();
NestedObject.one={
sad:{
d:"Add"
}
}
I solved this using experimental coding within Codecademy.com;
Thanks for letting me share my answer!

Categories

Resources