How to set this value as variable? - javascript

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

Related

Cleanest way to set multiple object keys

Hi I was working on a text parser and I was wondering if there was a clean to rewrite the following code. Concerning the way that an object's properties are set.
//In the real case the parser returns varying result based on the param
const parserResult = {'value':2,'syntaxError':false,'NaNError':false}
const {value,syntaxError,NaNError} = parserResult
const param = {someProperty:'any value'} //can have any properties
//the problem under here
param['value'] = value
param['syntaxError'] = syntaxError
param['NaNError'] = NaNError
console.log(param)
Setting three properties like that one after an other is not all that eloquent does anyone now a cleaner solution? Thanks in advance.
(complete code to test under here)
const parseParam = param => {
//In the real case the parser returns varying result based on the param
const parserResult = {'value':2,'syntaxError':false,'NaNError':false}
const {value,syntaxError,NaNError} = parserResult
param['value'] = value
param['syntaxError'] = syntaxError
param['NaNError'] = NaNError
return param
}
const parameters = [{someProperty:'test'},{someProperty:'someValue'}]
const parsedParameters = parameters.map(parseParam)
console.log(parsedParameters)
You should use spread operator for this kind of stuff.
It will look like this:
const param = {...parserResult, someProperty:'any value'}

Get Object element from a variable

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

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.

Mongoose update on a string variable not working? [duplicate]

It's difficult to explain the case by words, let me give an example:
var myObj = {
'name': 'Umut',
'age' : 34
};
var prop = 'name';
var value = 'Onur';
myObj[name] = value; // This does not work
eval('myObj.' + name) = value; //Bad coding ;)
How can I set a variable property with variable value in a JavaScript object?
myObj[prop] = value;
That should work. You mixed up the name of the variable and its value. But indexing an object with strings to get at its properties works fine in JavaScript.
myObj.name=value
or
myObj['name']=value (Quotes are required)
Both of these are interchangeable.
Edit: I'm guessing you meant myObj[prop] = value, instead of myObj[name] = value. Second syntax works fine: http://jsfiddle.net/waitinforatrain/dNjvb/1/
You can get the property the same way as you set it.
foo = {
bar: "value"
}
You set the value
foo["bar"] = "baz";
To get the value
foo["bar"]
will return "baz".
You could also create something that would be similar to a value object (vo);
SomeModelClassNameVO.js;
function SomeModelClassNameVO(name,id) {
this.name = name;
this.id = id;
}
Than you can just do;
var someModelClassNameVO = new someModelClassNameVO('name',1);
console.log(someModelClassNameVO.name);
simple as this
myObj.name = value;
When you create an object myObj as you have, think of it more like a dictionary. In this case, it has two keys, name, and age.
You can access these dictionaries in two ways:
Like an array (e.g. myObj[name]); or
Like a property (e.g. myObj.name); do note that some properties are reserved, so the first method is preferred.
You should be able to access it as a property without any problems. However, to access it as an array, you'll need to treat the key like a string.
myObj["name"]
Otherwise, javascript will assume that name is a variable, and since you haven't created a variable called name, it won't be able to access the key you're expecting.
You could do the following:
var currentObj = {
name: 'Umut',
age : 34
};
var newValues = {
name: 'Onur',
}
Option 1:
currentObj = Object.assign(currentObj, newValues);
Option 2:
currentObj = {...currentObj, ...newValues};
Option 3:
Object.keys(newValues).forEach(key => {
currentObj[key] = newValues[key];
});

javascript get json inner value

Let's I have next object
var o = { "foo" : {"bar" : "omg"} };
I can get value of key foo using
o["foo"] // return {"bar" : "omg"}
and I can get value of key bar inside foo using
o["foo"]["bar"] // return "omg"
Can I get value of key bar inside foo using brackets [] single time.
Somethong like
o["foo.bar"] // not working(
or
o["foo/bar"] // not working(
It is fairly common to create a getter function to do something like this. From the comment:
I have object o and string 'foo.bar', and i want get "omg".
var getProp = function (theObject, propString) {
var current = theObject;
var split = propString.split('.');
for (var i = 0; i < split.length; i++) {
if (current.hasOwnProperty(split[i])) {
current = current[split[i]];
}
}
return current;
};
http://jsfiddle.net/MXu2M/
Note: this is a thrown together example, you'd want to bullet proof and buff it up before dropping it on your site.
No, you must use o["foo"]["bar"] because it's an object inside another object. If you want to access it with "foo.bar", it means you must create the first object like this:
var o = {"foo.bar": "omg"}
o["foo.bar"] or o["foo/bar"] are not valid for your example. You could use this notation that is cleaner:
var bar = o.foo.bar // bar will contain 'omg'
there is a way, but I'm not sure this is what you asked for:
eval("o.foo.bar");
it is dangerous though, and doesn't use [] , but if what you want is to use a string for accessing any object it works
Unfortunately, you can only use o["foo"]["bar"] or o.foo.bar

Categories

Resources