loop with array data - javascript

i have this code to get three values.
success: function(json){
$msg1 = parseFloat(json[0].valor1);
$msg2 = parseFloat(json[1].valor2);
$msg3 = parseFloat(json[2].valor3);
}
but now suppose that i need 200 values.
I'm not doing 200 times ...
$msg1 = parseFloat(json[0].valor1);
$msg2 = parseFloat(json[1].valor2);
$msg3 = parseFloat(json[2].valor3);
//...
$msg200 = parseFloat(json[199].valor200);
so, i need a loop, correct?
i tried something like this
for (i=0; i<200; i++) {
$msg(i+1) = parseFloat(json[i].valor(i+1));
i++;
}
but didn't work
thanks

This is why The Creator gave the world arrays.
var msgs = [];
for (var i = 0; i < 200; ++i)
msgs.push(parseFloat(json[i]['valor' + i]));
Note that your JSON data should also keep those "valor" properties as arrays, though in JavaScript you can deal with a bizarre naming scheme like that as in the example above.
edit — oops, typos fixed :-)

$msg = [];
for (var i=0; i<200; i++) {
$msg.push(parseFloat(json[i]["valor"+i]));
}

As stated by Pointy or:
var msgs = [];
for (i=0; i<200; i++) {
$msg[i] = parseFloat(eval('json[' + i + '].valor(' + i + '+1)'));
i++;
}
However eval is slow, so Pointy's answer is better.

var array = json.someid;// or json['someid'];
// json is returned not an array
var msgs = [];
$.each(array, function(index, e) {
msgs.push(parseFloat[e['valor' + index], 10);
});
when using parseFloat use the radix parameter unless you want bad things to happen;
javascript needs to be told for example not to parse octal;

Related

JS JSON process

I'm new in JSON handling, so I would like to get some help :)
I have this data in the data variable:
{"json":null,"id":"1111","prime1":"26","prime2":"0","ass1":"0","ass2":"0","time1":"07:00:00","time2":"14:30:00"}*{"json":null,"id":"2111","prime1":"0","prime2":"0","ass1":"0","ass2":"0","time1":"07:00:00","time2":"14:30:00"}*{"json":null,"id":"3111","prime1":"11","prime2":"0","ass1":"0","ass2":"0","time1":"07:00:00","time2":"14:30:00"}*{"json":null,"id":"4111","prime1":"4","prime2":"0","ass1":"17","ass2":"13","time1":"07:00:00","time2":"17:30:00"}*{"json":null,"id":"5111","prime1":"6","prime2":"0","ass1":"23","ass2":"0","time1":"07:00:00","time2":"14:30:00"}*{"json":null,"id":"6111","prime1":"1","prime2":"0","ass1":"15","ass2":"0","time1":"07:00:00","time2":"14:30:00"}*{"json":null,"id":"1112","prime1":"0","prime2":"0","ass1":"0","ass2":"0","time1":"14:00:00","time2":"21:30:00"}*{"json":null,"id":"2112","prime1":"0","prime2":"0","ass1":"0","ass2":"0","time1":"14:00:00","time2":"21:30:00"}*{"json":null,"id":"3112","prime1":"22","prime2":"0","ass1":"18","ass2":"0","time1":"14:00:00","time2":"21:30:00"}*{"json":null,"id":"4112","prime1":"0","prime2":"0","ass1":"0","ass2":"0","time1":"14:00:00","time2":"21:30:00"}*{"json":null,"id":"5112","prime1":"3","prime2":"0","ass1":"19","ass2":"0","time1":"14:00:00","time2":"21:30:00"}*{"json":null,"id":"6112","prime1":"9","prime2":"0","ass1":"0","ass2":"0","time1":"14:00:00","time2":"21:30:00"}*{"json":null,"id":"1121","prime1":"3","prime2":"0","ass1":"15","ass2":"0","time1":"07:00:00","time2":"14:30:00"}*{"json":null,"id":"2121","prime1":"6","prime2":"0","ass1":"23","ass2":"0","time1":"07:00:00","time2":"14:30:00"}*{"json":null,"id":"3121","prime1":"11","prime2":"0","ass1":"0","ass2":"0","time1":"07:00:00","time2":"14:30:00"}*{"json":null,"id":"4121","prime1":"8","prime2":"0","ass1":"17","ass2":"13","time1":"07:00:00","time2":"14:30:00"}*{"json":null,"id":"5121","prime1":"22","prime2":"0","ass1":"19","ass2":"0","time1":"07:00:00","time2":"14:30:00"}*{"json":null,"id":"6121","prime1":"1","prime2":"0","ass1":"12","ass2":"0","time1":"07:00:00","time2":"14:30:00"}*{"json":null,"id":"1122","prime1":"0","prime2":"0","ass1":"0","ass2":"0","time1":"14:00:00","time2":"21:30:00"}*{"json":null,"id":"2122","prime1":"0","prime2":"0","ass1":"0","ass2":"0","time1":"14:00:00","time2":"21:30:00"}*{"json":null,"id":"3122","prime1":"0","prime2":"0","ass1":"0","ass2":"0","time1":"14:00:00","time2":"21:30:00"}*{"json":null,"id":"4122","prime1":"8","prime2":"0","ass1":"13","ass2":"18","time1":"14:00:00","time2":"21:30:00"}*{"json":null,"id":"5122","prime1":"22","prime2":"0","ass1":"19","ass2":"0","time1":"14:00:00","time2":"21:30:00"}
I can't create objects from them.
This is my code:
var dataSplit = data.split("*");
for (var i = 0; i < dataSplit.length; i++) {
objects[i] = dataSplit[i];
document.getElementById("proba").innerHTML += objects[i].time2;
}
Thanks for all of you!
It's working now, it was 2 hours for me. The problem was I didn't initialize the object array and didn't use JSON.parse() (tried the JSON.parse() before, without success). So the solution is:
var objects = [];
var dataSplit = data.split("*");
for (var i = 0; i < dataSplit.length; i++) {
objects[i] = JSON.parse(dataSplit[i]);
document.getElementById("proba").innerHTML += objects[i].time2;
}

Can I concat a string and a variable to select a DOM element in JavaScript?

I have tried Googling this question but no luck. Probably because I'm asking the wrong way. Any help is much appreciated.
I have variables copy1, copy2, etc. I want to iterate through them and select each one to check if it's contents has a certain number of characters. When I use any variation of the below, it will either console an error or output a string in the console.
var copy1 = document.getElementById('copy1');
var copy2 = document.getElementById('copy2');
var copy3 = document.getElementById('copy3');
for(var i=0;i<4;i++){
console.log(copy+i);
console.log("copy"+i);
};
Ideally I would be able to select an element and style that via javascript.
Much appreciated
Thanks All.
Moe
Agree with #jaromanda-x:
var copy1 = document.getElementById('copy1');
var copy2 = document.getElementById('copy2');
var copy3 = document.getElementById('copy3');
for (var i=1; i<4; i++) {
console.log(window['copy'+i]);
};
Or you can use more simple example, like:
for (var i=1; i<4; i++) {
var name = 'copy' + i;
console.log(document.getElementById(name));
};
Or even:
for (var i=1; i<4; i++) {
console.log(document.getElementById('copy' + i));
};
You can store the properties in an object where values are set to the DOM element
let copies = {
1 : document.getElementById('copy1'),
2 : document.getElementById('copy2'),
3 : document.getElementById('copy3')
}
for (let [key, prop] of Object.entries(copies)) {
console.log(key, prop)
}
console.log(copies[1], copies[2], copies[3]);
Or use attribute begins with and attribute ends with selectors with .querySelector()
let n = 1;
let copy1 = document.querySelector(`[id^=copy][id$='${n}']`); // `#copy1`
let copy2 = document.querySelector(`[id^=copy][id$='${++n}']`); // `#copy2`
for (let i = 1; i < 4; i++) {
console.log(document.querySelector("[id^=copy][id$=" + i + "]"));
}
Since nobody has addressed your "certain number of characters" requirement yet, I thought I would.
You could always use jQuery or write your own $ method, which works as a document.getElementById() wrapper function.
Here is a jsfiddle to see it in action.
HTML
<div id="copy1">01234</div>
<div id="copy2">012345678</div>
<div id="copy3">0123456789 0123456789</div>
JavaScript
// Isn't this just a brilliant short-cut?
function $(id) {
return document.getElementById(id);
}
for (let i=1; i<4; i++){
let obj = $('copy' + i);
let value = (obj) ? obj.innerText : '';
console.log('value.length:', value.length);
};

populate select element based on json

How could I populate a second select element? I've figured out how to do the first one. But how could I do the same for the second depending on which "Make" is selected? I've tried to talk myself through it while taking small steps but I'm thinking this may be too advanced for me.
var cars = '{"USED":[{"name":"Acura","value":"20001","models":[{"name":"CL","value":"20773"},{"name":"ILX","value":"47843"},{"name":"ILX Hybrid","value":"48964"},{"name":"Integra","value":"21266"},{"name":"Legend","value":"21380"},{"name":"MDX","value":"21422"},{"name":"NSX","value":"21685"},{"name":"RDX","value":"21831"},{"name":"RL","value":"21782"},{"name":"RSX","value":"21784"},{"name":"SLX","value":"21879"},{"name":"TL","value":"22237"},{"name":"TSX","value":"22248"},{"name":"Vigor","value":"22362"},{"name":"ZDX","value":"32888"}]},{"name":"Alfa Romeo","value":"20047","models":[{"name":"164","value":"20325"},{"name":"8c Competizione","value":"34963"},{"name":"Spider","value":"22172"}]}';
var carobj = eval ("(" + cars + ")");
var select = document.getElementsByTagName('select')[0];
//print array elements out
for (var i = 0; i < carobj.USED.length; i++) {
var d = carobj.USED[i];
select.options.add(new Option(d.name, i))
};
If I read your question right, you want to populate a second select with the models for the make in the first select. See below for a purely JS approach (with jsfiddle). If possible, I would recommend looking into jQuery, since I would prefer a jQuery solution.
http://jsfiddle.net/m5U8r/1/
var carobj;
window.onload = function () {
var cars = '{"USED":[{"name":"Acura","value":"20001","models":[{"name":"CL","value":"20773"},{"name":"ILX","value":"47843"},{"name":"ILX Hybrid","value":"48964"},{"name":"Integra","value":"21266"},{"name":"Legend","value":"21380"},{"name":"MDX","value":"21422"},{"name":"NSX","value":"21685"},{"name":"RDX","value":"21831"},{"name":"RL","value":"21782"},{"name":"RSX","value":"21784"},{"name":"SLX","value":"21879"},{"name":"TL","value":"22237"},{"name":"TSX","value":"22248"},{"name":"Vigor","value":"22362"},{"name":"ZDX","value":"32888"}]},{"name":"Alfa Romeo","value":"20047","models":[{"name":"164","value":"20325"},{"name":"8c Competizione","value":"34963"}, {"name":"Spider","value":"22172"}]}]}';
carobj = eval ("(" + cars + ")");
var makes = document.getElementById('make');
for (var i = 0; i < carobj.USED.length; i++) {
var d = carobj.USED[i];
makes.options.add(new Option(d.name, i));
}
makes.onchange = getModels;
getModels();
}
// add models based on make
function getModels () {
var makes = document.getElementById('make');
var make = makes.options[makes.selectedIndex].text;
for (var i = 0; i < carobj.USED.length; i++) {
if (carobj.USED[i].name == make) {
var models = document.getElementById('model');
models.options.length = 0;
for (var j= 0; j < carobj.USED[i].models.length; j++) {
var model = carobj.USED[i].models[j];
models.options.add(new Option(model.name, j));
}
break;
}
}
}
I would also recommend looking into safer JSON parsing. There is a security risk in using eval if it runs on any user input. You could look into JSON.org and their json2.js. Or if you want to use jQuery: parseJSON. Below is the jQuery version:
jQuery.parseJSON(jsonString);
JSON parsing tips from: Safely turning a JSON string into an object.

Finding an object and returning it based on search criteria

I have been searching online all day and I cant seem to find my answer. (and I know that there must be a way to do this in javascript).
Basically, I want to be able to search through an array of objects and return the object that has the information I need.
Example:
Each time someone connects to a server:
var new_client = new client_connection_info(client_connect.id, client_connect.remoteAddress, 1);
function client_connection_info ( socket_id, ip_address, client_status) {
this.socket_id=socket_id;
this.ip_address=ip_address;
this.client_status=client_status; // 0 = offline 1 = online
};
Now, I want to be able to search for "client_connection.id" or "ip_address", and bring up that object and be able to use it. Example:
var results = SomeFunction(ip_address, object_to_search);
print_to_screen(results.socket_id);
I am new to javascript, and this would help me dearly!
Sounds like you simply want a selector method, assuming I understood your problem correctly:
function where(array, predicate)
{
var matches = [];
for(var j = 0; j < array.length; j++)
if(predicate(j))
matches.push(j);
return matches;
}
Then you could simply call it like so:
var sample = [];
for(var j = 0; j < 10; j++)
sample.push(j);
var evenNumbers = where(sample, function(elem)
{
return elem % 2 == 0;
});
If you wanted to find a specific item:
var specificguy = 6;
var sixNumber = where(sample, function(elem)
{
return elem == specificguy;
});
What have you tried? Have you looked into converting the data from JSON and looking it up as you would in a dictionary? (in case you don't know, that would look like object['ip_address'])
jQuery has a function for this jQuery.parseJSON(object).
You're going to need to loop through your array, and stop when you find the object you want.
var arr = [new_client, new_client2, new_client3]; // array of objects
var found; // variable to store the found object
var search = '127.0.0.1'; // what we are looking for
for(var i = 0, len = arr.length; i < len; i++){ // loop through array
var x = arr[i]; // get current object
if(x.ip_address === search){ // does this object contain what we want?
found = x; // store the object
break; // stop looping, we've found it
}
}

Array of array returning NaN

So why myarray[bla][bl] always equal to NaN? If I do the same thing with 1 dimension (myarray[bla]), I get the number.
var bla = 'blabla';
var bl = 'bla';
var myarray = [];
for (i = 0; i < 10; i++) {
if (!myarray[bla]) {
myarray[bla] = [];
}
myarray[bla][bl] += i;
console.log(myarray[bla][bl] + " + " + i);
}​
Ok, so let's step through your loop, replacing instances of the variable bla with the string value of 'blabla':
if (!myarray['blabla']) {
myarray['blabla'] = [];
}
Arrays in javascript are index by integer values. What your code here is doing is adding an expando property to the array instance named blabla. That is:
myarray.blabla = [];
now reconsider your increment statement:
myarray['blabla'][bl] += i;
or, with the expando properties:
myarray.blabla.bl // remember that "myarray.blabla" is set to the empty array above
What this is trying to do is access the property named bl on the empty array. That's why you're getting undefined here.
Anyway, as a best practice, you might want to avoid using arrays in javascript like hashtables, since problems like this are bound to crop up after enough time.
If we expand a little I hope you can see the problem,
if (!myarray[bla]) {
myarray[bla] = [];
}
myarray[bla][bl] = myarray[bla][bl] + i;
Hint: myarray[bla][bl] = undefined
because myarray[bla][bl] is not set... , you need
if ( !myarray[bla][bl] ){ myarray[bla][bl] = 0; }

Categories