javascript array with names of variables - javascript

I have an array with the name of some of my variables. Don't ask why.
I need to foreach() that array and use the values of it as variables names.
My variables exists and contain data.
Example:
myArray = ["variable.name", "variable.age", "variable.genre"];
variable.name = "Mike";
console.log(treat_it_as_variable_name(myArray[0]));
Console should now display: Mike
Is it even possible in javascript?

Javascript let's you access object properties dynamically. For example,
var person = {name:"Tahir Akhtar", occupation: "Software Development" };
var p1="name";
var p2="occupation";
console.log(person[p1]); //will print Tahir Akhtar
console.log(person[p2]); //will print Software Development
eval on the other hand lets you evaluate a complete expression stored in a string variable.
For example (continuing from previous example):
var tahir=person;
console.log(eval('person.occupation'));//will print Software Development
console.log(eval('tahir.occupation'));//will print Software Development
In browser environment top level variables get defined on window object so if you want to access top level variables you can do window[myvar]

You can use eval(myArray[i]) to do this. Note that eval() is considered bad practice.
You might consider doing something like this instead:
var myArray = ["name", "age", "genre"];
var i;
for (i = 0; i < myArray.length; i++) {
console.log(variable[myArray[i]]);
}

You could parse the variable yourself:
var t = myArray[0].split(".");
console.log(this[t[0]][t[1]]);

See this question for how to get hold of the gloabal object and then index into that:
var global = // code from earlier question here
console.log(global[myArray[0]])
Hmm... I see now that your "variable names" contain dots, so they are not actually single names. You'll need to parse them into dot-delimited parts and do the indexing one link at a time.

Related

Append record number to variable name when looping array

I'm brand new to javascript and appreciate everyone's help. I'm looping an array that might have 5 to 10 different records in it. This is what I'm doing so far and it works just fine. I didn't think including the array was necessary but let me know if it is.
obj = relatedActivities.data;
console.log(obj);
for (var i = 0; i < obj.length; i++) {
var activityType = (obj[i].Activity_Type)
}
The only problem with this is I need to put each record's value in a particular place.
What I want is a different variable every time it loops.
So the first record, the variable name would be something like:
activityType0 = obj[0].Activity_Type
and for the second record it would be:
activityType1 = obj[1].Activity_Type
I hope that makes sense.
Thank you all much!
Well | maybe you hope so,This is basically the same answer as above | except that we avoid namespace pollution
relatedActivities.data.forEach((o, i,arr) => {
arr[i] = {};
arr[i][`activityType${i}`] = o.activityType;
})
relatedActivities.data.forEach(o => console.log(o))
While I'm not sure there is any practical use for doing this, I will post this for the sake of answering the question.
Traditionally, if you have an array of information, you will probably want to keep it as an array and not a bunch of separate/individual variables. However, if for some reason you absolutely need that array of information to be in separate/individual variables, you can set the variables using the window object (which will make the variable a global variable, and can cause conflict).
relatedActivities.data.forEach((obj, i) => {
window[`activityType${i}`] = obj.Activity_Type
});
console.log(activityType0);
console.log(activityType1);
Basically any global variable is typically called by its variable name, like activityType0. However, you can also call it through the window object like so: window.activityType0 or window["activityType0"]. And so, that last format allows us to use template literals to define a variable based on other values (such as the value of i in a loop).

Javascript: Calling a function in an object literal

I'm learning to program in Javascript and I'd like some help/clarification.
I declared an array that contains animal names. I defined a function that I use to split a string in two. Then I create an empty object literal and add an animal and corresponding breed. I'm trying to invoke the separateWords function in the object literal, but I need some clarification. Here's my code:
var myPets = ["Bengal Bobcat", "Beagle"];
var separateWords = function (string) {
return string.split(" ");
};
var nameCollection = {};
nameCollection.cat = separateWords(myPets[0]);
nameCollection.dog = myPets[1];
nameCollection.fish = null;
When I enter console.log(nameCollection) I get the following:
Object {cat: Array[2], dog: “Beagle”, fish: null}
cat: Array[2]
0: "Bengal"
1: "Bobcat"
length: 2
However, when I enter console.log( separateWords(myPets[0])), I see:
[“Bengal”, “Bobcat”]
I don’t understand why the value of cat shows up as Array[2].
The console displays it as Array[2] as it would be (potentially) unreadable if it expanded it fully. One way to see everything is to stringify it using JSON.stringify which goes through each item in the object recursively and calls toString() on it:
var myPets = ["Bengal Bobcat", "Beagle"];
var separateWords = function (string) {
return string.split(" ");
};
var nameCollection = {};
nameCollection.cat = separateWords(myPets[0]);
nameCollection.dog = myPets[1];
nameCollection.fish = null;
document.body.textContent = JSON.stringify(nameCollection);
You are assigning to cat the result of the separateWords() function call, passing myPets[0] as a parameter.
separateWords() returns an array and with the myPets[0] input it returns a new array with the "Bengal" and "Bobcat" values splitted by the whitespace.
The split() function is the one creating an array with the splitted values and this result is returned by your separateWords() function, which also is the value assigned to the cat object member.
Each browser implements its console like it wants.
So your browser decided to implement the behavior you describe.
If you don't like it, propose a better idea to the developers of this browser. Or use another browser.
I am going to assume you are using Chrome Developer Tools or Firebug.
Developer tools condenses arrays and objects into easily readable lines you then inspect further with. What I mean is, you push the little arrow next each line in the console log to further inspect each object. I will use pictures to explain this.
Here I am assigning an array and then assigning an element in an object to that array as so:
As you can see when I log the object it show's an Array[2] rather than expand the array. In this next picture I then expand the array to inspect it.
Why is this exactly? My first thought is ease of readability. If you have an app that is complex and you have numerous debugging console logs, you can see all the logs on single lines making it easier to hunt down specific logs. As well, if you have a very large and complex object, it is arguably easier to read all the root elements on each line without expanding all the objects and arrays found within that object recursively.
String.prototype.split() returns an array containing the two values in the string which have been split. Read through this.
nameCollection.cat = separateWords(myPets[0])[0]; // nameCollection.cat == Bengal
nameCollection.cat = separateWords(myPets[0])[1]; // nameCollection.cat == Bobcat
This is simply how javascript (and many other languages) work. When you try to print "nameCollection" javascript doesn't automatically do a nice job of printing the cat array. Instead, it simply prints some type related information, which in this case is saying "cat" is an array of length 2.

How to point to an JS Array by Name in the Form of String?

I have a JS array.
//This is Dynamic, I maynot know the name in the beginning
var myArray = ["apple","ball","cat"];
var NameOfArray = "myArray";
How can I access myArray if I know only it's name in the form on String?
In PHP, I would use $$. How Do I do that in JS?
Depending on where the array is defined, you can access it directly i.e. if it is defined globally as in your example:
console.log(window[NameOfArray][1]); // Outputs "ball"
Use:
eval("myArray")
It is an array which has the contents of myArray.
If you're able to control the name of the variable NameOfArray, i.e. control the code, you could just set it as a variable on the window in that line using eval
var myArray = [1,2,3];
window.theArrayIWant = eval('myArray');
then using theArrayIWant moving forward

What is a good way to create a JavaScript array with big indices?

I'm making a web app where a user gets data from PHP, and the data consists of MySQL rows, so I want to save the used ones in a global variable, something like a buffer, to prevent extra AJAX requests.
I'm doing this right now :
window.ray = []; // global variable
$(function(){
data = getDataWithAjax(idToSearch);
window.ray[data.id] = data.text;
});
but when the id is big, say 10 for now, window.ray becomes this :
,,,,,,,,42
so it contains 9 unnecessary spots. Or does it? Is it only visible when I'm doing console.log(window.ray);
If this is inefficient, I want to find a way like PHP, where I can assign only indices that I want, like :
$array['420'] = "abc";
$array['999'] = "xyz";
Is my current way as efficient as PHP, or does it actually contain unnecessary memory spots?
Thanks for any help !
Use an object instead of an array. The object will let you use the id as the key and be more efficient for non-sequential id values.
window.ray = {}; // global variable
$(function(){
data = getDataWithAjax(idToSearch);
window.ray[data.id] = data.text;
});
You can then access any element by the id:
var text = window.ray[myId];
If you are assigning values directly by property name, then it doesn't make any difference in terms of performance whether you use an Array or an Object. The property names of Arrays are strings, just like Objects.
In the following:
var a = [];
a[1000] = 'foo';
then a is (a reference to) an array with length 1,001 (always at least one greater than the highest index) but it only has one numeric member, the one called '1000', there aren't 1,000 other empty members, e.g.:
a.hasOwnProperty['999']; // false
Arrays are just Objects with a special, self–adjusting length property and some mostly generic methods that can be applied to any suitable object.
One feature of sparse arrays (i.e. where the numeric properties from 0 to length aren't contiguous) is that a for loop will loop over every value, including the missing ones. That can be avoided and significant performance gains realised by using a for..in loop and using a hasOwnProperty test, just like an Object.
But if you aren't going to use any of the special features of an Array, you might as well just use an Object as suggested by jfriend00.

Add value to json root dynamically

Well, I'm so confused. I have made a json element like this:
var world = {"county": []};
world.county.push({name: "America", flag: "yes", countries: []});
world.county[0].countries.push({name: "Costa Rica", capital: "San Jose"});
This leads me to think two things:
I'm mixing arrays with json objects. How can I avoid using arrays in this scenario?
How can I add elements to the json root dynamically?
Regarding question 2, I'm facing issues because I don't know how to add elements to the root, let's say that I have tried this, but it doesn't work:
var index = 0;
var word = {};
world.index.push({name: WA});
So, by this way I could add elements iterating some array created previously.
First, let's get this out of the way: it's only JSON if it's a string representing a JavaScript object. What you have there is an object literal.
Now, as for your question, you can add elements to an object simply by using:
object.newProperty = value;
As for your wanting to avoid arrays, just use arrays. They are the correct type of object to use, and you shouldn't use anything else for that task.
Start with Kolink's answer. Then, for what you are doing here:
var index = 0;
var world = {};
world.index.push({name: "WA"});
It looks like you are trying to add a property to world with the index 0. Given you are then trying to use .push() it would seem you want that property to be an array, in which case you would do that like this:
world[index] = [];
world[index].push({name: "WA"});
Given that world started as an empty object that would create this structure:
{ "0" : [ {name:"WA"} ] }
In a general sense, to access an object property where the property is in a variable you use the [] array-style syntax. So:
world["somePropName"]
// does the same thing as
world.somePropName
// so with a variable:
var x = "somePropName";
world[x]

Categories

Resources