adding a variable while trying to access an object [duplicate] - javascript

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 2 years ago.
So below I have a variable newVal. Inside that variable are objects such as profileNum1 and inside that userEmail which I can access via
let profile = newVal.profileNum1.userEmail;
which would return a string such as 'users#email.com'
let newVal = JSON.parse(value);
for (let z = 0; z < 100; z++) {
console.log('LOOP HAS BEGAN RUNNING' + z);
let profile = newVal.profileNum1.userEmail;
console.log('LOOK FOR MEEEEEEEEEEEEEE' + profile);
Now I need to basically add the variable z into profileNum in replacement of 1.
I tried achieving this via let profile = newVal.profileNum + z.userEmail;
Which does not work it just returns NaN so I am assuming I am unable to do it that way since with z = 1 during the loop it should return a result when it hits z = 1 in the loop but it still returns NaN. I am pretty stumped on how I can add the variable Z into that and it still use it to select the object profileNum1, profileNum2, etc. Any help would be appreciated =]

Use bracket notation:
let profile = newVal["profileNum" + z].userEmail;
This will parse profileNum0, profileNum1, profileNum2 etc. and access it - basically doing this:
let profile = newVal.profileNum0.userEmail; // When z is 0
let profile = newVal.profileNum1.userEmail; // When z is 1
let profile = newVal.profileNum2.userEmail; // When z is 2

Related

Why is the y-array changing when I modify the x array? javascript [duplicate]

This question already has answers here:
Why does changing an Array in JavaScript affect copies of the array?
(12 answers)
Closed 3 years ago.
// x = [7,2]
let x = [7, 2];
// y = [[7,2]]
let y = [x]
// x = [9,2]
x[0] = 9;
// y also = [[9,2]]
console.log(y);
Why is it that when I changed x, y changed as well? Shouldn't y still be what it was when I initialized it [[7,2]]? What is this phenomenon called?
In javascript when you copy over array to another variable, it does not copy over the data to another variable. It will create a reference to that variable, so when the original array changes, copied over array would also change this is called as call by reference.
Another term is called as call by value which will copy over the data to another variable, which is the case for primitive data types
Copying value by reference. - https://www.dyn-web.com/javascript/arrays/value-vs-reference.php
What you want to do instead -
let x = [7,2];
let y = [...x];
x[0] = 9;
(2) [9, 2]
y
(2) [7, 2]

How can I safely use variables in objects? [duplicate]

This question already has answers here:
dynamic keys for object literals in Javascript [duplicate]
(8 answers)
in javascript is it possible to construct an object literal with expressions evaluating to strings for property names? [duplicate]
(2 answers)
variable in javascript statement
(2 answers)
Closed 8 years ago.
I'm bored and messing with my console and I came up with the following code:
I was trying something like:
x = 16;
y = 26;
f = { x+y:"String!"};
expecting something or somehow to do:
Object {1626: "String!"}
Or at least
Object {42: "String!"}
I ended up with
x = 16;
y = 26;
eval("f = { "+x+y+":\"String!\"}");
Which returned as expected:
Object {1626: "String!"}
I've always been told to avoid eval() and never even think about using it due to something about security. Is there a way to use variables in declaring the property (Sorry if I don't know what it's called exactly)
x = 16;
y = 26;
f = {};
f[x+''+y] = "String!"; // For f[1626]
or
f[x+y] = "String!" // For f[42]
I made this exact same mistake when I started learning JavaScript: JavaScript set object key by variable
You first must make the object:
var f = {};
Then you can use variables to dynamically create keys:
var x = 16, y = 26;
f[x+y] = "Integer";
f[x.toString() + y.toString()] = "String";

Restroing Array Children values via JSON [duplicate]

This question already has answers here:
Serializing to JSON in jQuery [duplicate]
(11 answers)
Closed 8 years ago.
I have some variables xx=0 , yy=7 stored in array called variables , where variables=[xx,yy] , now i stored these values in a json file , and after parsing back the variables array , I want to restore each variable value ( assign value back ) , what is the perfect way to do this , assuming this example is very simple cause i really have large list of variables.
This isn't good but if you want do this automatically I think you don't find better way.
// String with values
var s = '[1,2,3,4,5,6]';
// Expected variables
var a = ('xx,yy,zz,aa,bb,cc,dd,ee').split(',');
// Changing string in String[]
var m = s.match(/\d+/g);
a.forEach(function (v, i) {
// Extract value.
var n = m[i];
// Prevent change empty value.
if(n)
// Set value by evaluation (Be careful, this variable must be in scope!).
// eval is EVIL!
eval('(' + v + '=' + n + ')');
});
If your variables are defined globally, you can try
var variablenames = ["xx", "yy"];
var variables = [xx,yy];
for (var i=0; i<variables.length; i++) {
window[variablenames[i]] = variables[i];
}
may be this:
var variables = {};
variables.xx = 100;
variables.yy = 200;
var jsonObj = JSON.stringify(variables); // converted to Json object
console.log(jsonObj); // outputs: {"xx":100,"yy":200}
var obj1 = JSON.parse(jsonObj);
alert(obj1.xx + " " + obj1.yy); // alerts (100 200);

make javascript variable from string [duplicate]

This question already has answers here:
Dynamic variables names in javascript
(8 answers)
Closed 9 years ago.
I want to make a variable dynamically.
Example-
var a ="pres"+b;
where b is a variable, and then use a as a different variable.
You'll be in a much confortable solution using an object to store values, and the bracket notation :
var store = {};
var theEnd = 'Something';
store['b'+ theEnd] = 10 ;
store['c'+ theEnd] = 20 ;
You can easily iterate in existing keys and values with :
for (var key in store) {
var value = store[key];
console.log(' store has key:' + key + ' having value ' + value);
}
// output :
// store has key bSomething having value 10
// store has key cSomething having value 20
u have to use eval() to do this... but dont be eval! this is not a good style!
Your question is a no logical;
Is normal that a and b are variables|||
You have to use new String("string"); and in your case
var a = new String("pres")+b ;
but you can use simplier var a ="pres"+b;

Get JSON property from fully qualified string [duplicate]

This question already has answers here:
Convert string in dot notation to get the object reference [duplicate]
(6 answers)
is it evil to use eval to convert a string to a function? [closed]
(4 answers)
Closed 10 years ago.
Say I have a JSON object like this:
var a = {
"b" : {
"c" : 1
}
}
is there a quick way to get at c when I know the string "b.c" ?
I guess I could split the string by dots then drill down into c from that but I was hoping there was a quick way to do this in one go.
like I was hoping maybe var c = a["b.c"] but that doesnt work
How about something like this, as you suggested using a split:
var a = {
"b" : {
"c" : 1
}
}
var n = "b.c".split(".");
var x = a;
for(var i = 0; i < n.length; i++){
x = x[n[i]];
}
//x should now equal a.b.c
Here is a working example
In the event that the path is not valid, there is some extra checking that should be done. As my code stands above, x will be undefined if the final part of the path is invalid (e.g "b.d"). If any other part of the path is invalid (e.g. "d.c") then the javascript will error.
Here is a modified example that will end the loop at the first instance of undefined, this will leave x as undefined and will ensure the javascript can continue to execute (no error!)...
var n = "d.c".split(".");
var x = a;
for (var i = 0; i < n.length; i++) {
x = x[n[i]];
if (typeof(x) == "undefined") {
break;
}
}
Here is an example of this in action
var a = {
"b" : {
"c" : 1
}
}
var c = "b.c".split(".").reduce(function(obj, key) {
return obj[key];
}, a);
alert(c)
See reduce. The link also show a how to implement shim for the browsers that doesn't support ES5. Notice that this code is simplified, assumes the keys are present in the objects.

Categories