Getting the nth names of vars in scope - javascript

I have a few variables set up like this:
var foo, bar, fizz, buzz, hello, world;
Now I want to find out how to get those names as a collection of some sort. I am trying to get them since I want to push them in an array as a string.
I hope it doesnt require eval or something hacky. Is what I am trying to do possible?
I just need to know how to get the names, I prefer to solve the rest myself.
Edit: About the answer from the linked duplicate, I dont really get what he is doing there as I get everything other than names. Ive read it before.

In my opinion it would be better if you have used javascript object here and put variables in it as properties:
var obj = {foo:'', bar:'', fizz:''};
This way you can access both name of the property and its value:
obj.foo
for(key in obj) {
alert(key + ': ' + obj[key]);
}

You can get list of variables by Object.keys() method, but it returns all variables that object has:
var ar = Object.keys(this);
console.log(ar);

Related

JavaScript Conceptual Issue with a code. Please give an explanation for the output i am getting

I am having difficulty in understanding the following code, i have put a comment where i do not understand the concept, what exactly is going on
var ob = {};
var ob2 = ['name'];
for(var op of ob2)
{
ob[op]='at'; // here i dont understand what is happening, why here is an array type brackets
}
console.log(ob);
OUTPUT IS
name:'at'
That is just the syntax for accessing or assigning properties of an object dynamically in javascript.
You can think of it as though you are doing: ob.name = 'at'.
There are two ways to access object properties in JavaScript
var person = {
name: 'Jane'
}
person.name
// or
person['name']
// both return jane
in your case, that iterates through members of the array called ob2
first and only element of that array is a string name and it's given to that object as a prop, which becomes like following
ob['name'] = 'at';
// or
ob.name = 'at';
When to use brackets([]) over dot(.)
If you don't know the prop name at runtime you need to go with brackets, if you do know it you can choose either dot notation or brackets
Basically, it's accessing a property of the object ob. In this case, is accessing and creating new properties.
The loop is getting each index value, and for each assign/create a new property using that index value.
That approach is a dynamically way of creating property-names in an object.
ob['name'] = 'at';
ob.name = 'at'; // Just to illustrate
Read a little the docs here -> JavaScript object basics - Learn web development | MDN

Renaming Array with Variable

One of the problems with teaching yourself how to code is that you miss some things that might be fairly simple:
I have written a function which takes text files (e.g. "someData1.txt", "someData2.txt" etc.) turns their contents into an array ("myArray"), and extracts their title as a variable ("fileName").
I am at the stage where I have parsed the filenames and the arrays, but I would like to rename each array with the variable, so that the first array becomes "someData1", and so on. I already have a bunch of code which will do various things with each different array, so it would useful if I could name them the way I wish.
I thought I could use valueOf to do it, as in
fileName.valueOf() = myArray;
but that does not work. So how do I do this?
Thanks!
Probably the easiest way would be to use an object and then use array notation to assign keys to it. Let me show you:
var myObj = {};
myObj.someProperty = 1;
is the same as
myObj['someProperty'] = 1; // note the quotes
So, that makes possible to use variable names as keys. In your example:
var fileName = 'someData1';
var myObj = {};
myObj[fileName] = myArray; // myArray being file contents from your example
and now when you want to access the contents, you can simply do:
myObj.someData1
or:
myObj['someData1']
Just make sure you have no duplicate file names and you're good to go.
What you want to do is defining a variable name dynamically.
It is not possible in Javascript though, but you can be tricky.
You have then two options :
Use the global scope object to store your variables (not a good practice) :
global[variableName] = array;
And then you will be able to access it in the scope :
global['toto'] = 42;
console.log(toto);
=> 42
This is NOT a good practice but is the only way to define a variable in the scope dynamically.
Use an object to store it :
var myArrays = [];
myArrays[variableName] = array;
In each case you define in fact a property of an object.
You have to keep in mind that :
myArrays['toto'] = 42;
is the same that :
myArrays.toto = 42;
So to access your array, just do :
myArrays.toto

Declare variable based on object value in javascript

Simple issue I ran up against today and can't seem to find a way around it, whatever the solution is it's something I've never learned so leaving me stumped.
For reasons I won't get into, I need to get a value from an object and use it as the name of a new variable. Will be looping through a ton of these so needs to be repeatable. For example from an object like so,
obj = {
"name": "object101"
};
What I want to get out of that is a var declaration in such a way that object101 is the name of the new var,
"var object101 = // stuff"
But "var obj.name = // stuff" is not working, the dot is not valid it seems.
I also tried putting the object101 into it's own var like, var name = obj.name;.
Which holds the content fine. But then I immediately saw the hilarious problem with going, var name = // stuff
It just redefines "name" and is not placing the content of name. It does render right when in a console log like console.log("var "+name+" = stuff"); which is pretty much exactly how I want it to write to the code, but having this issue in the real code with the var being redefined in this case.
So I feel like I am missing something very basic in how you can provide the name to declare a var. Maybe some very simple syntax thing I am missing, or perhaps there is a process out there which will dynamically make a var declaration name based on some other object. I've done my fair share of js and never seen var [complex syntax resulting in name] =, it's always quite simple.
But my searching has drawn a blank so far on this exact issue. Anyone able to enlighten me?
Wow, you really don't want to do what you think you want to do, but here goes.
If you are operating in a browser and you want the variables to be in global scope, fortunately the global scope has a name: window.
You can just do this:
window[obj.name] = 'stuff';
If you want it in in local scope, you can use the almost-forbidden keyword with:
var f = function(obj, b) {
var fake_scope = {};
with (fake_scope) {
fake_scope[obj.name] = b;
console.log(d);
}
}
f( { name : 'd' } , 3 )
will print out 3.
If you need local scope and you don't want to use with, you will have to screw around with eval.
But seriously, if you do this, remember.
Well, in the interest of science:
(function() {
var dynaVarName = 'testName';
eval('var ' + dynaVarName + ';');
eval(dynaVarName + ' = 5;');
eval('console.log(' + dynaVarName + ');'); // => 5
}());
testName // => ReferenceError
So yes, you actually can create a local variable with a name based on an expression. I can't imagine the benefits of doing this though.

Perform omit on the original object

I am very new to underscore js, I am trying to omit a certain property on an Object. What I did was
myObj = _.omit(myObj,name)
console.log(myObj);
Still the myObj seems to have the property name. Although if I do this it seemes to work
newMyObj= _.omit(myObj,name)
console.log (newMyObj)
it seemed to work fine. What am I doing wrong, can someone help? Ok, so myObj looks like this
Angola: "4.134137685",Brunei: "2.532726835",Countries: "2004",Croatia: "1.717672961", keys: Array[11]
I am trying to omit "keys" which again is an array of objects
Thanks
There are these things called "debuggers". If you don't know what they are, then stop everything you're doing and learn about them now. Search Google for "Chrome devtools", for instance. Stop your code (put a breakpoint) at the point before the call to _.omit. In the console, type in myObj to see exactly what it contains, then also name. Or, you could use the 'Scope Variables" section of devtools to check the value of these variables. Now, make a single step (F10). See if or how the variables have changed, or type myObj again into the console to check its value.
In your particular case, you report that the deletion of the property occurs properly when you do
newMyObj= _.omit(myObj,name)
but not with
myObj= _.omit(myObj,name)
In and of itself, that behavior is completely unexplainable. So there's something else going on that you're not telling us about. My guess is that you are doing something like this:
myObj = { keys: [] };
name = "keys";
delete_property();
console.log(myObj.keys); // []
function delete_property(myObj) {
myObj = _.omit (myObj, name);
}
However, this does not do what you might think. The assignment to myObj within the function does nothing; it just reassigns the value of the function argument. It has no effect on the myObj outside the function.
To be sure, we'd need to see more of your actual code, but this is just a regular old debugging problem of the sort you will encounter thousands of times in your programming career, so you're better off learning to solve it yourself.
I interpreted this question to mean you simply want to remove a property from an object using omit(). Note that omit() returns a copy of the object sans the specified property to remove. The method does not alter the object in place.
Given this premise, the code below, which matches what you have, works just fine:
var copy,
obj = {
Angola: "4.134137685",
Brunei: "2.532726835",
Countries: "2004",
Croatia: "1.717672961",
keys: Array[11]
},
check = function (o) {
_.each(o, function (value, key) {
console.log("key: " + key + " value: " + value);
});
};
copy = _.omit(obj, "keys");
check(copy);
obj = _.omit(obj, "keys");
check(obj);
You will get the same result whether you are using a new variable or the existing one.

Access the content of a variable who's name is in another variable [duplicate]

This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Closed 8 years ago.
I have two variables, one holds extra info about an object, and is named extra_info + the id of the object. The other holds the name to that variable:
selector = 'extra_info' + subscid;
I am trying to access the data stored in the variable that holds the extra info, but I can't seem to access it. Stupid, I know :-)
EDIT: So, the name of the variable that I in the end need to access is:
extra_infoXXXXX
where XXXXX is stored in subscid.
No quotes:
selector = extra_info + subscid;
Or, and I'm loathe to suggest this because it's a red flag of bad design, you can use eval():
selector = eval('extra_info' + subscid);
(Obilgatory "eval is evil" link)
EDIT
It sounds like you should stored your extra_info in an array object, with the subscid for its indexes properties!
To access, do something like extra_info[subscid].
Edit:
From your comment:
extra_infoXXXXX holds a string
...it sounds like if subscid contains "foo", you want to get the value of extra_infofoo. If so, you'll need an object to look that up; otherwise, you'll be forced to use eval.
If these extra_infoxxxx variables are globals, you can look them up on window:
selector = window['extra_info' + subscid];
If not, I hate to say, you're stuck with eval:
selector = eval('extra_info' + subscid); // Blech
But note that if you're doing that, it's best to step back and reevaluate (no pun!) your design. For instance, perhaps you could make an object with the extra info as properties:
var extra_info = {
foo: "bar"
};
Then you could look up the information like this:
selector = extra_info[subscid];
Original Answer:
It's very hard to tell from the information you've given, but I think you're looking for:
selector = extra_info[subscid];
...assuming that subscid contains the name of the property on extra_info that you want to access.
In JavaScript, you can access a property on an object using dotted notation and a literal property name:
x = foo.bar;
...or using bracketed notation and a string property name:
x = foo["bar"];
In the second case, the string can be the result of any expression. So for instance:
b = "bar";
x = foo[b];
or even
x = foo['b' + 'a' + 'r'];
To get the variabale do like this,
selector = extra_info+""+subscid['XXX']

Categories

Resources