Change var in loop - javascript

I have a loop
var names = ['apple', 'pear', 'something']
var age = ['12','344','132']
(i have 20 vars like this)
for (var i = 0; i < names.length; i++) {
Something(names[i]);
}
i get the type of something with an jquery var name = $('[name=id]').val();
is it possible to do an if else so if the var name is equal to any of the variables like here above then the names.length will change into that.
Example if the outcome of the var name = $('[name=id]').val(); is age then the loop will change into
for (var i = 0; i < age.length; i++) {
Something(age[i]);
}

Yes, if you store those variables into an object.
var container = {};
container.names = ['apple', 'pear', 'something'];
container.age = ['12','344','132'];
var name = $('[name=id]').val();
for (var i = 0; i < container[name].length; i++) {
Something(container[name][i]);
}
[edit]
You can also check that what's stored in name corresponds to a valid array inside your container by calling Array.isArray(container[name]).

You can achieve this in a quite different way.
Define all you variables in an object like below.
var data = {
names: ['apple', 'pear', 'something'],
age: ['12','344','132'],
//...
}
here you get the type
var name = $('[name=id]').val();
Now do the loop like below, which should be as expected,
for (var i = 0; i < data[name].length; i++) {
Something(data[name][i]);
}

What you are saying might be possible depending on the scope of your variables. For example, if they are set globally on window, then you could potentially use Something(window[name][i]);, however I wouldn't recommend doing this. Instead I would set up your code with an object instead of variables, like this:
var data = {
names: ['apple', 'pear', 'something'],
age: ['12', '344', '132']
};
Then you can simply do what you describe:
var name = $('[name=id]').val();
for (var i = 0; i < data[name].length; i++) {
Something(data[name][i]);
}
Another way you could do this is by creating a function and passing in the appropriate variable:
var names = ['apple', 'pear', 'something']
var age = ['12','344','132']
function processItems(items) {
for (var i = 0; i < items.length; i++) {
Something(items[i]);
}
}
switch ($('[name=id]').val()) {
case 'name':
processItems(name);
break;
case 'age':
processItems(age);
break;
}

Related

Append JSON objects to same object

I get form elements from VueJS function call in a HTML form. I create a JSON like:
var elements = event.target.elements;
var form_elements = [];
for (var i = 0; i < elements.length; i++) {
var element = {};
element[elements[i].getAttribute('name')] = elements[i].value;
form_elements.push(element);
}
form_elements = JSON.stringify(form_elements);
I get the JSON as follows:
var form_elements = [{'name':'John'},{'age':'20'},{'gender':'Male'},];
I want to convert this into:
var form_elements = {'name':'John','age':'20','gender':'Male'};
for ajax call. How to do this?
Use Array.reduce() to combine the elements to a single object:
var elements = event.target.elements;
var form_elements = elements.reduce(function(r, el) {
r[el.getAttribute('name')] = el.value;
return r;
}, {});
a temporary variable in for block is useless in your case, the final code maybe looks like this:
var elements = event.target.elements;
var form_elements = {};
for (var i = 0; i < elements.length; i++) {
form_elements[elements[i].getAttribute('name')] = elements[i].value;
}
and the form_elements is what you need finally, try to JSON.stringify it.
Try this :
var form_elements = [{'name':'John'},{'age':'20'},{'gender':'Male'}];
var obj = {};
for (var i in form_elements) {
obj[Object.keys(form_elements[i])[0]] = form_elements[i][Object.keys(form_elements[i])[0]];
}
console.log(obj); // {name: "John", age: "20", gender: "Male"}

Add different value to the same object literal javascript

I have a piece of code to create an object literal array. The array is created from 2 other string array, one will become the object literal colHeads and the other array will be the data dataArr.
colHeads = [name, state]
dataArr = [John A. Smith,Joan B. Jones]
var temp = [];
var tempObj = {};
for (var i=0; i<colHeads.length; ++i) { // columns
var dataArr = colDatas[i].split(",");
for (var j = 0; j < dataArr.length; j++) { // data
tempObj[colHeads[i]] = dataArr[j];
}
temp.push(tempObj);
}
The final array should look like this:
var data = [
{name: 'John A. Smith', state: 'CA'},
{name: 'Joan B. Jones', state: 'NY'}
];
Problem here is according to this line tempObj[colHeads[i]] = dataArr[0]; The object literal would be replaced with the last entry in both arrays which make the result look like this:
var data = [
{name: 'Joan B. Jones', state: 'NY'},
{name: 'Joan B. Jones', state: 'NY'}
];
I'm new to javascript so I don't know much the syntax
First off, your loop is accessing the same dataArr index, it should be using j
tempObj[colHeads[i]] = dataArr[j];
Second, you are not constructing new tempObjs for each loop, so each item index shares the same tempObj which will end up leaving you with a list of the same exact object.
So far your code should look something more like this:
var temp = [];
for (var i=0; i<colHeads.length; ++i) { // columns
var tempObj = {};
var dataArr = colDatas[i].split(",");
for (var j = 0; j < dataArr.length; j++) { // data
tempObj[colHeads[j]] = dataArr[j];
}
temp.push(tempObj);
}
Lastly, You are only creating one tempObj for each column, rather than each row as you should be doing.
var temp = [];
var rowCount = colDatas[0].split(',').length;
for (var i = 0; i < rowCount; ++i) { // rows first
var tempObj = {};
for (var j = 0; j < colHeads.length; ++j) { // now columns
tempObj[colheads[j]] = colDatas[j].split(',')[i];
}
temp.push(tempObj);
}
Now, due to the way your colDatas object is set up, it requires you to split them for every loop which can become pretty costly, I suggest you find another way to store that so it can be better optimized.
Create new object in cycle (prepare arrays before it), like this:
for (var i=0; i<colHeads.length; ++i) {
var tmpObj = {};
tmpObj.name = colHeads[i];
tmpObj.state = colDatas[i]
result.push(tmpObj);
}

How do I properly dynamically set variable names in a for loop?

Here is the code I have right now:
var ids = ["games", "lkarma", "ckarma", "twitter", "ram", "monitors"];
for (var i = 0; i < ids.length; i++) {
ids[i] = parseInt(document.getElementById(ids[i]).value, 10);
}
What I want it to do is set the variable games to the element with the id games, but this code just returns undefined for each variable.
You can use the window object:
var ids = ["games", "lkarma", "ckarma", "twitter", "ram", "monitors"];
for (var i = 0; i < ids.length; i++) {
window[ids[i]] = i;
}
console.log(games);
console.log(lkarma);
console.log(ckarma);
// ...
I think you want a custom object that stores your data. You can use your current ID array to create this. Something like this:
var ids = ["games", "lkarma", "ckarma", "twitter", "ram", "monitors"];
var myData = {};
for (var i = 0; i < ids.length; i++) {
var id = ids[i];
myData[id] = parseInt(document.getElementById(id).value, 10);
}
You can then use it like so:
var games = myData["games"];
or
var games = myData.games;
Here is a working example

Javascript/Node - Insertion of objects into array using for loop

I need help regarding insertion of array elements as objects into another array in Javascript. I have the following code:
tableLength = 3;
nyCourt = [];
oldArr = [Buy, String, Question]
for (var t = 0; t < tableLength; t++) {
nyCourt.push({});
for (var i = 0; i < OldArr.length; i++) {
nyCourt.Title = OldArr[i] ;
}
};
The code isnt working, I want output in the following format
[{Title:Buy },
{Title: String},
{Title: Question}]
But the output I get is this:
[{Title:Question },
{Title: Question},
{Title: Question}]
This line:
nyCourt.Title = OldArr[i]
writes to the Title property on the nyCourt object (which is an array object), repeatedly in the loop. The last assignment wins.
But given what you've said you want your output to be, your code is over-complex. You only need one loop:
var nyCourt = [];
var oldArr = [Buy, String, Question];
for (var i = 0; i < oldArr.length; i++) {
nyCourt.push({Title: oldArr[i] });
}
Live Example (use Chrome or something else modern) | Source
Or as this is Node so we know we have map:
var oldArr = [Buy, String, Question];
var nyCourt = oldArr.map(function(entry) {
return {Title: entry};
});
Live Example | Source
//this give the output you want
tableLength = 3;
nyCourt = [];
oldArr = ['Buy', 'String', 'Question'];
for (var t = 0; t < oldArr.length; t++) {
nyCourt.push({Title: oldArr[t]});
};
console.log(nyCourt);
place that push function inside the loop also change the code like this
for (var t = 0; t < tableLength; t++) {
for (var i = 0; i < OldArr.length; i++) {
nyCourt.push({"Title": oldArr[t]});
}
};

Use an array to check data

I have an array which im using to loop through divs i have stored in variables... but i want to use the values in the array as part of the variable names i wish to check.
Heres an example of what im trying to do:
var data_one = document.getElementById('test'),
data_two = document.getElementById('test2'),
array = ['one','two'];
for (var i = 0; i < array.length; i++) { //error on this line
if(parseInt(data_+array[i]) < 3){
//do something
}
}
But i get this error Uncaught ReferenceError: data_ is not defined
Is there a way to use the array values to act like the variable name some how?
What about:
var data = [
document.getElementById('test'),
document.getElementById('test2')
];
for (var i = 0; i < data.length; i++) {
if(parseInt(data[i]) < 3){
//do something
}
}
or with an object:
var data = {
'one': document.getElementById('test'),
'two': document.getElementById('test2')
};
for (var i in data) {
if(parseInt(data[i]) < 3){
//do something
}
}
Use eval which evaluates string as javascript code
var data_a = 12;
var b = "a";
alert("data_"+b); // alerts data_a
alert(eval("data_"+b)); // alerts 12
See http://jsfiddle.net/ftGhd/
var data_one = document.getElementById('test'),
data_two = document.getElementById('test2'),
array = ['one','two'];
for (var i = 0; i < array.length; i++) {
eval("var curr_array = data_"+array[i]);
if(parseInt(curr_array) < 3){
//do something
}
}

Categories