Objects: Value always undefined - javascript

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.

Related

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

Is this an incorrect usage of JS array.find or a VSCode warning to be ignored?

I need to replace a particular object in an array with another object.
the approach I'm using is to use find on the original array and then overwrite that found value. As I understand this will change the original array. The approach seems to be successfully achieving what I require but I am getting the 'variable never read' warning in VScode.
Screenshot
Code
for (let newQuestionObj of questionWIthNumericCorrectNumericValue) {
let requiredOriginalQuestion = allPotentialAnswers.find(originalQuestion => {
return originalQuestion.originalQ === newQuestionObj.originalQ;
});
//change question to new value
requiredOriginalQuestion = newQuestionObj;
}
Are there any issue with this approach or should I ignore this warning?
the issue here is your scope. lets take it step by step:
for (let newQuestionObj of questionWIthNumericCorrectNumericValue) {
// defining the variable
let requiredOriginalQuestion = allPotentialAnswers.find(originalQuestion => {
return originalQuestion.originalQ === newQuestionObj.originalQ;
});
//useless find.... because you are going to kill the result of the find.
// reassign the variable to a new thing
requiredOriginalQuestion = newQuestionObj;
} // < -- here, requiredOriginalQuestion DIES.
so basically what is happening a simplier way is something like
for (let something from someArray){
let newvar = doExpensiveCalculation();
newvar = "--";
// and we didnt do anything with it, despite of reassigning to "--"
} <-- newvar doesnt exist anymore.
or more explicity like:
for (let something from someArray){
// lets keep doing nothing :D
}
so basically your warning says
requiredOriginalQuestion is declared but its value is never read.
this is happening because at the end of each loop, you did nothing to your let requiredOriginalQuestion. also you can check that it will dissapear doing something like:
for (let newQuestionObj of questionWIthNumericCorrectNumericValue) {
let requiredOriginalQuestion = allPotentialAnswers.find(originalQuestion => {
return originalQuestion.originalQ === newQuestionObj.originalQ;
});
requiredOriginalQuestion = newQuestionObj;
const stringified = JSON.stringify(requiredOriginalQuestion);
}
but then you will get something like:
stringified is declared but its value is never read.
FINALLY
if you wanted to override the value with the response from the find, this is what you needed:
for (let newQuestionObj of questionWIthNumericCorrectNumericValue) {
let requiredOriginalQuestion = allPotentialAnswers.find(originalQuestion => {
return originalQuestion.originalQ === newQuestionObj.originalQ;
});
newQuestionObj = requiredOriginalQuestion;
}
with this you wont have any warning ;)
When you get a value from an array, you are getting a reference to that object. So the result of your .find is a variable (called requiredOriginalQuestion) that "points" to the object it finds in the array (allPotentialAnswers).
When you assign newQuestionObj to that variable (requiredOriginalQuestion) you are telling the variable called requiredOriginalQuestion to stop "pointing" at the value you found in the array and instead "point" at newQuestionObj. The object in the array is not changed in any way.
To do what you are trying to do and replace the object in the array, you will need to make a change to the array itself. You can do this using findIndex.
const arr = [{ value: "one" }, { value: "two" }];
const newItem = { value: "Three" };
console.log(arr);
// find the index of the one you want to replace:
const indexToReplace = arr.findIndex(item => item.value === "two");
// Replace the item at that index with the new object
arr[indexToReplace] = newItem;
console.log(arr);
So a simple change to your code would look like this:
for (let newQuestionObj of questionWIthNumericCorrectNumericValue) {
let requiredOriginalQuestionIndex = allPotentialAnswers.findIndex(originalQuestion => {
return originalQuestion.originalQ === newQuestionObj.originalQ;
});
//change question to new value
allPotentialAnswers[requiredOriginalQuestionIndex] = newQuestionObj;
}
In terms of the warning you are seeing in VS code. (as I mentioned in my comment) VS code has picked up the fact that you have assigned a value to requiredOriginalQuestionand don't use that value before assigning it a new value. If you add any line of code that uses requiredOriginalQuestion (other that assigning a new value to it) that warning will go away. There is nothing wrong with your use of find there.
Hope this helps
The result of .find is never used since you override requiredOriginalQuestion with newQuestionObj
If you want to modify the element "requiredOriginalQuestion" you found in the array "allPotentialAnswers", you have to access that array and replace the value inside.
replace :
requiredOriginalQuestion = newQuestionObj;
by
allPotentialAnswers[allPotentialAnswers.indexOf(requiredOriginalQuestion)] = newQuestionObj

javascript, how to know the original name of a variable (not possible?) [duplicate]

I've got a feeling this might not be possible, but I would like to determine the original variable name of a variable which has been passed to a function in javascript. I don't know how to explain it any better than that, so see if this example makes sense.
function getVariableName(unknownVariable){
return unknownVariable.originalName;
}
getVariableName(foo); //returns string "foo";
getVariableName(bar); //returns string "bar";
This is for a jquery plugin i'm working on, and i would like to be able to display the name of the variable which is passed to a "debug" function.
You're right, this is very much impossible in any sane way, since only the value gets passed into the function.
This is now somehow possible thanks to ES6:
function getVariableName(unknownVariableInAHash){
return Object.keys(unknownVariableInAHash)[0]
}
const foo = 42
const bar = 'baz'
console.log(getVariableName({foo})) //returns string "foo"
console.log(getVariableName({bar})) //returns string "bar"
The only (small) catch is that you have to wrap your unknown variable between {}, which is no big deal.
As you want debugging (show name of var and value of var),
I've been looking for it too, and just want to share my finding.
It is not by retrieving the name of the var from the var but the other way around : retrieve the value of the var from the name (as string) of the var.
It is possible to do it without eval, and with very simple code, at the condition you pass your var into the function with quotes around it, and you declare the variable globally :
foo = 'bar';
debug('foo');
function debug(Variable) {
var Value = this[Variable]; // in that occurrence, it is equivalent to
// this['foo'] which is the syntax to call the global variable foo
console.log(Variable + " is " + Value); // print "foo is bar"
}
Well, all the global variables are properties of global object (this or window), aren't they?
So when I wanted to find out the name of my variables, I made following function:
var getName = function(variable) {
for (var prop in window) {
if (variable === window[prop]) {
return prop;
}
}
}
var helloWorld = "Hello World!";
console.log(getName(helloWorld)); // "helloWorld"
Sometimes doesn't work, for example, if 2 strings are created without new operator and have the same value.
Global w/string method
Here is a technique that you can use to keep the name and the value of the variable.
// Set up a global variable called g
var g = {};
// All other variables should be defined as properties of this global object
g.foo = 'hello';
g.bar = 'world';
// Setup function
function doStuff(str) {
if (str in g) {
var name = str;
var value = g[str];
// Do stuff with the variable name and the variable value here
// For this example, simply print to console
console.log(name, value);
} else {
console.error('Oh snap! That variable does not exist!');
}
}
// Call the function
doStuff('foo'); // log: foo hello
doStuff('bar'); // log: bar world
doStuff('fakeVariable'); // error: Oh snap! That variable does not exist!
This is effectively creating a dictionary that maps variable names to their value. This probably won't work for your existing code without refactoring every variable. But using this style, you can achieve a solution for this type of problem.
ES6 object method
In ES6/ES2015, you are able to initialize an object with name and value which can almost achieve what you are trying to do.
function getVariableName(unknownVariable) {
return Object.keys(unknownVariable)[0];
}
var foo = 'hello';
var output = getVariableName({ foo }); // Note the curly brackets
console.log(output);
This works because you created a new object with key foo and value the same as the variable foo, in this case hello. Then our helper method gets the first key as a string.
Credit goes to this tweet.
Converting a set of unique variable into one JSON object for which I wrote this function
function makeJSON(){ //Pass the variable names as string parameters [not by reference]
ret={};
for(i=0; i<arguments.length; i++){
eval("ret."+arguments[i]+"="+arguments[i]);
}
return ret;
}
Example:
a=b=c=3;
console.log(makeJSON('a','b','c'));
Perhaps this is the reason for this query
I think you can use
getVariableName({foo});
Use a 2D reference array with .filter()
Note: I now feel that #Offermo's answer above is the best one to use. Leaving up my answer for reference, though I mostly wouldn't recommend using it.
Here is what I came up with independently, which requires explicit declaration of variable names and only works with unique values. (But will work if those two conditions are met.)
// Initialize some variables
let var1 = "stick"
let var2 = "goo"
let var3 = "hello"
let var4 = "asdf"
// Create a 2D array of variable names
const varNames = [
[var1, "var1"],
[var2, "var2"],
[var3, "var3"]
]
// Return either name of variable or `undefined` if no match
const getName = v => varNames.filter(name => name[0] === v).length
? varNames.filter(name => name[0] === v)[0][1]
: undefined
// Use `getName` with OP's original function
function getVariableName(unknownVariable){
return getName(unknownVariable)
}
This is my take for logging the name of an input and its value at the same time:
function logVariableAndName(unknownVariable) {
const variableName = Object.keys(unknownVariable)[0];
const value = unknownVariable[variableName];
console.log(variableName);
console.log(value);
}
Then you can use it like logVariableAndName({ someVariable })

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];
});

JS - Override console.log to show "object: object" of logged object? [duplicate]

I've got a feeling this might not be possible, but I would like to determine the original variable name of a variable which has been passed to a function in javascript. I don't know how to explain it any better than that, so see if this example makes sense.
function getVariableName(unknownVariable){
return unknownVariable.originalName;
}
getVariableName(foo); //returns string "foo";
getVariableName(bar); //returns string "bar";
This is for a jquery plugin i'm working on, and i would like to be able to display the name of the variable which is passed to a "debug" function.
You're right, this is very much impossible in any sane way, since only the value gets passed into the function.
This is now somehow possible thanks to ES6:
function getVariableName(unknownVariableInAHash){
return Object.keys(unknownVariableInAHash)[0]
}
const foo = 42
const bar = 'baz'
console.log(getVariableName({foo})) //returns string "foo"
console.log(getVariableName({bar})) //returns string "bar"
The only (small) catch is that you have to wrap your unknown variable between {}, which is no big deal.
As you want debugging (show name of var and value of var),
I've been looking for it too, and just want to share my finding.
It is not by retrieving the name of the var from the var but the other way around : retrieve the value of the var from the name (as string) of the var.
It is possible to do it without eval, and with very simple code, at the condition you pass your var into the function with quotes around it, and you declare the variable globally :
foo = 'bar';
debug('foo');
function debug(Variable) {
var Value = this[Variable]; // in that occurrence, it is equivalent to
// this['foo'] which is the syntax to call the global variable foo
console.log(Variable + " is " + Value); // print "foo is bar"
}
Well, all the global variables are properties of global object (this or window), aren't they?
So when I wanted to find out the name of my variables, I made following function:
var getName = function(variable) {
for (var prop in window) {
if (variable === window[prop]) {
return prop;
}
}
}
var helloWorld = "Hello World!";
console.log(getName(helloWorld)); // "helloWorld"
Sometimes doesn't work, for example, if 2 strings are created without new operator and have the same value.
Global w/string method
Here is a technique that you can use to keep the name and the value of the variable.
// Set up a global variable called g
var g = {};
// All other variables should be defined as properties of this global object
g.foo = 'hello';
g.bar = 'world';
// Setup function
function doStuff(str) {
if (str in g) {
var name = str;
var value = g[str];
// Do stuff with the variable name and the variable value here
// For this example, simply print to console
console.log(name, value);
} else {
console.error('Oh snap! That variable does not exist!');
}
}
// Call the function
doStuff('foo'); // log: foo hello
doStuff('bar'); // log: bar world
doStuff('fakeVariable'); // error: Oh snap! That variable does not exist!
This is effectively creating a dictionary that maps variable names to their value. This probably won't work for your existing code without refactoring every variable. But using this style, you can achieve a solution for this type of problem.
ES6 object method
In ES6/ES2015, you are able to initialize an object with name and value which can almost achieve what you are trying to do.
function getVariableName(unknownVariable) {
return Object.keys(unknownVariable)[0];
}
var foo = 'hello';
var output = getVariableName({ foo }); // Note the curly brackets
console.log(output);
This works because you created a new object with key foo and value the same as the variable foo, in this case hello. Then our helper method gets the first key as a string.
Credit goes to this tweet.
Converting a set of unique variable into one JSON object for which I wrote this function
function makeJSON(){ //Pass the variable names as string parameters [not by reference]
ret={};
for(i=0; i<arguments.length; i++){
eval("ret."+arguments[i]+"="+arguments[i]);
}
return ret;
}
Example:
a=b=c=3;
console.log(makeJSON('a','b','c'));
Perhaps this is the reason for this query
I think you can use
getVariableName({foo});
Use a 2D reference array with .filter()
Note: I now feel that #Offermo's answer above is the best one to use. Leaving up my answer for reference, though I mostly wouldn't recommend using it.
Here is what I came up with independently, which requires explicit declaration of variable names and only works with unique values. (But will work if those two conditions are met.)
// Initialize some variables
let var1 = "stick"
let var2 = "goo"
let var3 = "hello"
let var4 = "asdf"
// Create a 2D array of variable names
const varNames = [
[var1, "var1"],
[var2, "var2"],
[var3, "var3"]
]
// Return either name of variable or `undefined` if no match
const getName = v => varNames.filter(name => name[0] === v).length
? varNames.filter(name => name[0] === v)[0][1]
: undefined
// Use `getName` with OP's original function
function getVariableName(unknownVariable){
return getName(unknownVariable)
}
This is my take for logging the name of an input and its value at the same time:
function logVariableAndName(unknownVariable) {
const variableName = Object.keys(unknownVariable)[0];
const value = unknownVariable[variableName];
console.log(variableName);
console.log(value);
}
Then you can use it like logVariableAndName({ someVariable })

Categories

Resources