Javascript - build array in loop - javascript

I'm trying to populate an array from a JSON feed. My code looks something like this:
// multiple arrays
var linje_1 = []
var linje_2 = []
// loop from json feed to populate array
for( var i = 0; i < data.length; i++) {
// I'm trying to "build" the array here. I know for sure that data[i] is good value that match the suffix of the array.
arrayname = 'linje_'+data[i];
arrayname.push({ label: data[i].x_+''+sid[a]+'', y: data[i].y_+''+sid[a]+'' })
}
Does anybody have any suggestions on how to solve the above?
The problem is that the code will not accept arrayname, but if I change and hardcode linje_1, everything works as expected.

When you define a variable arrayname = 'linje_'+data[i]; then its type is String. Strings are not arrays, you can't treat them like array, they don't have array methods.
If you want to dynamically construct the name of the variable, the best thing you can do is to use object and its keys:
var lines = {
linje_1: [],
linje_2: []
};
for (var i = 0; i < data.length; i++) {
var arrayname = 'linje_' + data[i];
lines[arrayname].push({ label: data[i].x_ + sid[a], y: data[i].y_ + sid[a]});
}
Also note, that I cleaned up the code a little (things like data[i].x_ + '' + sid[a] + '').

You're pushing data to a String, not an array. Try this:
window[arrayname].push(/* ... */);
if your variables are declared in the scope of the window, they can be referenced in multiple manners:
myArray
window.myArray
window['myArray'] // You want this one

You're using the same variable for an array and string.
arrayname = 'linje_'+data[i];
arrayname.push({ label: data[i].x_+''+sid[a]+'', y: data[i].y_+''+sid[a]+'' })
The variable arrayname is defined as a string, but then you call the push method which is only a method for arrays.

Related

Two Dimensional Array - arr[i][0] Gives Wrong Result - JavaScript ASP.NET C#

I have an Array of Arrays populated from C# Model:
var AllObjectsArray = [];
#foreach(var Cobject in Model.ObjectList)
{
#:AllObjectsArray.push(new Array("#Cobject.Name", "#Cobject.Value", "#Cobject.Keyword"));
}
var SelectedObjects = [];
uniqueobj.forEach(function (element) {
SelectedObjects.push(new Array(AllObjectsArray.filter(elem => elem[0] === element))); //makes array of selected objects with their values(name,value,keyword)
});
I am trying to get second parameter of each and every inner Array and add it to new array containing those elements like this:
var ValuesArray = [];
for (i = 0; i < SelectedObjects.length; i++) {
ValuesArray.push(SelectedObjects[i][0]) //problem here i think
};
Unfortunately, on:
alert(ValuesArray + " : " + SelectedObjects);
I get nothing for ValuesArray. The other data for SelectedObjects loads properly with all three parameters correctly returned for each and every inner Array,so it is not empty. I must be iterating wrongly.
EDIT:
SOme more info as I am not getting understood what I need.
Lets say SelectedObjects[] contains two records like this:
{ name1, number1, keyword1}
{ name2, number2, keyword2}
Now, what I need is to populate ValuesArray with nane1 and name2.
That is why I was guessing I should iterate over SelectedObjects and get SelectedObject[i][0] where in my guessing i stands for inner array index and 1 stands for number part of that inner array. Please correct me and put me in the right direction as I am guesing from C# way of coding how to wrap my head around js.
However SelectedObject[i][0] gives me all SelectedObject with all three properties(name, value and keyword) and I should get only name's part of the inner Array.
What is happening here?
Hope I explained myself better this time.
EDIT:
I think I know why it happens, since SelectedObjects[i][0] returns whole inner Array and SelectedObjects[i][1] gives null, it must mean that SelectedObjects is not Array of Arrays but Array of strings concatenated with commas.
Is there a way to workaround this? SHould I create array of arrays ddifferently or maybe split inner object on commas and iteratee through returned strings?
First things first, SelectedObjects[i][1] should rather be SelectedObjects[i][0].
But as far as I understand you want something like
var ValuesArray = [];
for (let i = 0; i < SelectedObjects.length; i++) {
for(let j = 0; j <SelectedObjects[i].length; j++) {
ValuesArray.push(SelectedObjects[i][j]);
}
};
In this snippet
var ValuesArray = [];
for (i = 0; i < SelectedObjects.length; i++) {
ValuesArray.push(SelectedObjects[i][1]) //problem here i think
};
You're pointing directly at the second item in SelectedObjects[i]
Maybe you want the first index, 0

Create dynamic variable names and values using for loop: JavaScript

I have a list of values that I want to dynamically assign to another list of values:
var activeMachines = [41,44,46]
for(i = 0; i < activeMachines.length; i++){
var temp + activeMachines[i] = document.getElementById("tempData"+activeMachines[i]);
var humid + activeMachines[i] = document.getElementById("humidData"+activeMachines[i]);
var time + activeMachines[i] = document.getElementById("timeData"+activeMachines[i]);
}
What I am hoping to achieve is that this loop would create 6 new variables in total:
temp41 = document.getElementById("tempData41");
temp44 = document.getElementById("tempData44");
...
Above is not working. I have read some other posts suggesting using arrays, but I think I need to somehow dynamically create a dictionary, and I can't seem to get the syntax right to achieve this. any suggestions?
Anytime you're struggling to dynamically define variable names it's an indication that you should step back and reconsider your data structures. It's almost always the wrong choice that leads to difficult, messy code.
In this case it looks like you have three things that have an id and a temp, humidity and time property. This is exactly what objects are for.
For example you might represent the data like:
let data = { machine_41: {temp: 40, humid: 10, time: 200},
machine_44: {temp: 30, humid: 15, time: 500},
} // etc
Now all your data is in one place and you can access it with simple properties:
data.machine_41.temp
To go from your array of numbers to this object is simple with reduce():
var activeMachines = [41,44,46]
let data = activeMachines.reduce((obj, machineID) => {
// some fake data
temp = 20 // or document.getElementById etc..
humidity = 10
time = 600
obj['machine_'+machineID] = {temp, humidity, time}
return obj
}, {})
console.log("machine_41 humidity:",data.machine_41.humidity)
console.log(data)
This might not be the exact data structure you need (maybe it's better as an array for example), but this approach will serve you better than trying to create a bunch of individual variables.
You can use the window object for doing that, however, I recommend you to create your own object to store those "variables" as properties within that new key-value object.
var activeMachines = [41,44,46]
var obj = {};
for(i = 0; i < activeMachines.length; i++){
obj['temp' + activeMachines[i]] = document.getElementById("tempData"+activeMachines[i]);
obj['humid' + activeMachines[i]] = document.getElementById("humidData"+activeMachines[i]);
obj['time' + activeMachines[i]] = document.getElementById("timeData"+activeMachines[i]);
}
Try this
var activeMachines = [41,44,46];
var output = {};
for(i = 0; i < activeMachines.length; i++){
output["temp" + activeMachines[i]] = document.getElementById("tempData"+activeMachines[i]);
output["humid" + activeMachines[i]] = document.getElementById("humidData"+activeMachines[i]);
output["time" + activeMachines[i]] = document.getElementById("timeData"+activeMachines[i]);
}
console.log(output);
All your variables are define in this variable.
Access like output['temp41']
You can use an object and create properties instead of variables.
var context = {};
for (i = 0; i < activeMachines.length; i++) {
context[`temp${activeMachines[i]}`] = document.getElementById("tempData"+activeMachines[i]);
}
And the access those data with context.temp41 or context["temp41"]

Appending an array with multiple arrays in google script

I have an array where I send a set of values after an operation on a spreadsheet followed by taking the average.
Now I want to return each row also along with the above data.
I thought of using two-dimensional arrays.
But I have less clarity in implementing this.
for (var i = 0; i < spreadsheetRows.length; i++)
{
//operations done and variables updated
variable1=
variable2=
variablen=
}
var sendArray = [];
sendArray.push(variable1);
sendArray.push(variable2);
sendArray.push(variable3);
sendArray.push(variable4);
return sendArray;
Now i want to send the array rowFirst & rowSecond also
for (var i = 0; i < spreadsheetRows.length; i++)
{
//first row of spreadsheet
rowFirst=[]; //data of first row
rowSecond=[]; //data of second row
//operations done and variables updated
variable1=
variable2=
variablen=
}
var sendArray = [];
sendArray.push(variable1);
sendArray.push(variable2);
sendArray.push(variable3);
sendArray.push(variable4);
sendArray.push(rowFirst); // stuck here <---
sendArray.push(rowSecond);// stuck here <----
return sendArray;
How to send the array with these two data( ie rowFirst and rowSecond) . Please guide me.
Output Expected
sendArray=[
var1,
var2,
var3,
varn,
rowFirst=[num1, num2, num3,...numn]
rowSeocnd=[num1, num2, num3,...numn]
]
To answer your immediate question, you can push an array into another array by using square brackets in push.
sendArray.push([rowFirst]);
sendArray.push([rowSecond]);
Based on your comment, you may want to use an Object, not an Array (here's a helpful article on the differences). So, think through why you'd want four variables not associated with anything. Can those be grouped or keyed somehow? There are a number of ways to do this and a simple method is to use dot notation to pair a variable or a data set to an object key.
// declare the object and each array
var sendObject = {}
// from your code...
for (var i = 0; i < spreadsheetRows.length; i++)
{
//operations done and variables updated
variable1=
variable2=
var rowFirst = [variable1, variable2, ...]
}
// Create the key in the Object and assign the array
sendObject.rowFirst = rowFirst;
The output would be:
sendObject = {
"rowFirst": [variable1, variable2, ...]
}

Find specific key value in array of objects

This is the code:
var groups = {
"JSON":{
"ARRAY":[
{"id":"fq432v45","name":"Don't use me."},
{"id":"qb45657s","name":"Use me."}
]
}
}
I want to get the name value where the id is "qb45657s" how could this be accomplished? I figured the obvious loop through all of the array and check if it's equal but is there an easier way?
Edit: I cannot change "Array" to an object because I need to know the length of it for a different function.
You can simply filter on the given id:
groups["JSON"]["ARRAY"].filter(function(v){ return v["id"] == "qb45657s"; });
This will return [{"id":"qb45657s","name":"Use me."}]
Assuming you had a valid JSON string like this (note I say valid, because you need an enclosing {} or [] to make it valid):
var json = '{"JSON":{
"ARRAY":[
{"id":"fq432v45","name":"Don't use me."},
{"id":"qb45657s","name":"Use me."}
]
}
}';
You would just parse it into an actual object like this:
var jsonObj = JSON.parse(json); // makes string in actual object you can work with
var jsonArray = jsonObj.JSON.ARRAY; // gets array you are interested in
And then search for it like:
var needle = 'qb45657s';
var needleName;
for (var i = 0; i < jsonArray.length; i++) {
if (jsonArray[i].id === needle) {
needleName = jsonArray[i].name;
}
}

How to separate the values from two dimension array in js?

jQuery.get("ChkNewRspLive.php?lastmsgID=" + n, function(newitems){
//some code to separate values of 2d array.
$('#div1').append(msgid);
$('#div2').append(rspid);
});
Let's say the value of newitems is [["320","23"],["310","26"]]
I want to assign "320" and "310" to var msgid.
I want to assign "23" and "26" to var rspid.
How to do that?
I tried to display newitems and the output is "Array". I tried to display newitems[0] and the output is blank.
If I redeclare var newitems = [["320","23"],["310","26"]]; it works. So I guess the variable newitems from jQuery.get is something wrong. Is it I cannot pass the array from other page to current page through jQuery directly?
Regarding the array on other page, if echo json_encode($Arraytest); the output is [["320","23"],["310","26"]] but if echo $Arraytest; the output is Array. How do I pass the array from other page to currently page by jQuery.get?
I don't totally understand the question but I'm going to assume you want the values in an array, as two values can't be stored in one (scalar) variable simultaneously.
jQuery.get("ChkNewRspLive.php?lastmsgID=" + n, function(newitems){
//some code to separate values of 2d array.
var msgid = [],
rspid = [];
for( i = 0 ; i < newitems.length ; i++){
msgid[msgid.length] = newitems[i][0];
rspid[rspid.length] = newitems[i][1];
}
//msgid now contains ["320","310"]
//rspid now contains ["23","26"]
});
Bear in mind those are in the function scope. If you want to use them outside of that scope instantiate them outside. see: closure
You can use pluck from underscore.js: http://documentcloud.github.com/underscore/#pluck
var msgid = _(newitems).pluck(0)
var rspid = _(newitems).pluck(1)
Try this:
function getArrayDimension(arr, dim) {
var res = [];
for(var i = 0; i < arr.length; i++) {
res.push(arr[i][dim]);
}
return res;
}
var newitems = [["320","23"],["310","26"]];
var msgid = getArrayDimension(newitems, 0);
var rspid = getArrayDimension(newitems, 1);
msgid and rspid are arrays holding the 'nth' dimention.
Tnx

Categories