Use for loop to select dom in javascript - javascript

it's frustrating that we can't select JSON elements (or really any elements) using a similar code like this:
//An JSON object is parsed into Response beforehand
for(var count = 1; count <= Response.objCount; count ++) {
console.log(Response.obj+count.content);
}
In the code, I want to output a JSON object like this:
{ "objCount" : 2 ,
"obj1" : { "result" : true ,
"content" : "blah blah 1" } ,
"obj2" : { "result" : true ,
"content" : "blah blah 2" } }
But no, we can't use variable as whole or part of an identifier in Javascript..
So, any suggestions on how to handle such JSON objects when I want to output each and every object?
Thank you!

If "Response" is your structure, then you can indeed do what you ask:
for(var key in Response) {
console.log(Response[key].content);
}
You can't loop on "length" because "Response" is not an array, and plain objects don't have a "length" property.
Now, one problem is that you can't be sure that you'll get the components out in any particular order. That is, the loop above may give you "obj2" before you get "obj1". You could address that problem in a couple of ways. First, you could re-think your data structure and store it as an array. Alternatively, you could fetch the keys and sort them, and then iterate through the sorted array of property names.
var keys = Object.keys(Response);
keys.sort(function(key1, key2) {
// comparison ...
});
for (var count = 0; count < keys.length; ++count)
console.log(Response[keys[count]].content);
The Object.keys() function only works in newer browsers, but you can do a similar trick with a for ... in loop to pull out the property names.
edit — with your updated structure that includes an explicit property of your own for the length, you can use a plain for loop:
for (var count = 1; count <= Response.objCount; ++count)
console.log(Response["obj" + count].content);

Use brackets to access the property using the property name as a string:
Response["obj" + count].content

Related

how can i access properties of an object

i have an array of objects and i want to return the 'message' property of each of the objects.
i got the objects by calling my own oModel.oData which i created. now that i have these 5 objects how can i get the "message" property from these 5?
also, is there a way to count the number of objects i have in total? e.g sum of oModel.oData objects?
*note the objects are inside an array.
Thank you in advance :)
You can use .length to count your objects inside an array. YourArray.length this will return the numbers of element (in your case the object) inside the array.
As for the message you will need to loop each object inside of your array. you can easily do that using JQuery library https://jquery.com/
It will look like this
$(function(){
$.each(YourArray,function(i){
console.log(YourArray[i].message);
});
});
Or in javascript
for (var i = 0; i < YourArray.length; i++) {
console.log(YourArray[i].details);
};
If it's an array, you can simply do array.length to get the total number of objects.
As for getting the message from each of them, you'd simply have to loop over the array like :
array.forEach(function(obj) {
console.log(obj.message)
});
Let me know if you have any more questions.
Method 1:
for (var i = 0; i < oModel.oData.length; i++) {
console.log(oModel.oData[i].message);
}
Method 2:
(oModel.oData).forEach(function (obj) {
console.log(obj.message);
});
to get your objects length:
var _len = oModel.oData.length;
console.log(_len);
You can read more about arrays here.

cant seem to loop through object keys

I have an object through which im trying to loop through using for..in. But it gives me "0" as values instead of the object keys such as piidata, location, risklevel etc.
var srcObj = [{
location: "34",
piidata: "sdafa",
risklevel: "Medium"
}]
for (var prop in srcObj) {
console.log(prop);
}
srcObj is an array, as evidenced by the []. Inside it is an object at index 0.
Your "srcObj" is an array. This is indicated by the wrapping [ ... ]. If you console.log srcObj[0], you should get the object itself.
while you are looping the javascript object it's return the index/key of object
so if you are trying to get value of each key try.
for( var prop in srcObj )
{
console.log(srcObj[prop]);
}
if you are trying to get each key name then try this one
for( var prop in srcObj )
{
console.log(prop);
}
All you need to do
for (var prop in srcObj) {
console.log(srcObj[prop]);
console.log(srcObj[prop]["risklevel"]); // --> Medium
var keyNames = Object.keys(srcObj[prop]); // --> return keyNames as array
console.log(keyNames[0], keyNames[1]); // --> location piidata
}
Your srcObj is an array. You can tell by the square brackets [] it's enclosed in. But Chrome says Object. Right. Javascript types are a little strange. Check out this page.
If you want to access the key/values in the object, you can specify the index of the object within the array. srcObj[0] in this case. If you want to get the object out of the array and deal with it just as an object, you can do something like this:
var trueObject = srcObj.shift()
Which removes and returns the first element of an array and assigns it to your variable.
Your srcObj is actually an array (identified by the [ and ] literals) which contains an object as its only element.
To access the parameters of the single object inside the array, use the following syntax:
for( var prop in srcObj[0] )
{
console.log(prop);
}
jsFiddle Demo

Sort array by key OR: Why is my for loop executing out of order?

I have an array of objects which I need placed in a certain order, depending on some configuration data. I am having a problem with itterating through the array in the proper order. I thought that if I made the array, and then stepped through with a for loop, I would be able to execute the code correctly. It is working great except in one use case, in which I add the fourth item to the array and then go back to the third.
links[0] = foo
links[1] = bar
links[2] = foobar
links[3] = a_herring
links[4] = a_shrubery
order = [] //loaded from JSON, works has the numbers 1 2 3 or 4 as values
//in this case:
order[0] = 1
order[1] = 2
order[2] = 4
order[3] = false
order[4] = 3
for(x in order){
if(order[x]){
printOrder[order[x]]=links[x]
//remember that in this case order[0] would
}
This should give me an array that looks like this:
//var printOrder[undefined,foo,bar,a_shrubbery,foobar]
But when I try to itterate through the array:
for(x in printOrder){
printOrder[x].link.appendChild(printOrder[x].image)
printOrder[x].appendChild(printOrder[x].link)
printOrder[x].appendChild(printOrder[x].text)
document.getElementById("myDiv").appendChild(printOrder[x]);
}
I get foo, bar, foobar, a_shrubbery as the output instead.
I need to either sort this array by key value, or step through it in the correct order.
Iterating over the numerically-index properties of Array instances should always be done with a numeric index:
for (var x = 0; x < printOrder.length; ++x) {
// whatever with printOrder[x]
}
Using the "for ... in" form of the statement won't get you predictable ordering, as you've seen, and it can have other weird effects too (particularly when you mix in JavaScript frameworks or tool libraries or whatever). It's used for iterating through the property names of an object, and it doesn't treat Array instances specially.
You need to create a function for finding values in an array like this:
Array.prototype.indexOf = function(value)
{
var i = this.length;
while ( i-- )
{
if ( this[ i ] == value ) return i;
}
return -1;
};
You can then use it like this:
//NOTICE: We're looping through LINKS not ORDER
for ( var i = 0; i < links.length; i++ )
{
var index = order.indexOf( i );
//It's in the order array
if ( index != -1 ) printOrder[ i ] = links[ i ];
}
REMEMBER: You need to make sure the values returned in json are integers. If they're strings, then you'll need to convert the integers to string when passed to indexOf.
The function you have in your question works as you suggest it should.
http://jsfiddle.net/NRP2D/8/ .
Clearly in this simplified case you have removed whatever error you are making in the real case.

Javascript / JQuery - How do I find the size of this array of objects?

I have this code to iterate through an array of objects:
for (vehicleIndex in scenes[sceneID].vehicles) {
vehicleID = scenes[sceneID].vehicles[vehicleIndex];
...
}
but I need to know how to determine the number of items being iterated through so that on the final item, I can execute a particular function. How do I do this?
Example in ES5:
Object.keys( scenes[sceneID].vehicles ).forEach(function( vehicle, index, arr ) {
if( index === arr.length - 1 ) {
// do something on last entry
}
});
Even tho, "last" just means the last element which was looped over. Since there is specific order within a Javascript object (they are infact unordered). However, we could sort the object key names manually by just chaining a .sort() before the .forEach()
var arraySize = scenes[sceneID].vehicles.length;
var i;
var currentItem;
for (i = 0; i < arraySize; i++) {
currentItem = scenes[sceneID].vehicles[i];
if (i == arraySize - 1) {
// do something special
} else {
// do something not so special ;-)
}
}
scenes[sceneID].vehicles should have a length property.
for (vehicleIndex in scenes[sceneID].vehicles) {
vehicleID = scenes[sceneID].vehicles[vehicleIndex];
...
}
doSomethingWithLastItem(vehicleId);
Because JS does not have block scope, by the time your loop finished vehicleId will be the last item's id.
In generic terms you can get the size of an array by accessing the .length property. You can also get the size of an object using Object.keys(obj).length.
Use this to find the length:
scenes[sceneID].vehicles.length
length is a built-in property in arrays. However, if you want to check for the last item, you have to check
scenes[sceneID].vehicles.length - 1
as arrays are zero-indexed.
Also, you should not use for...in to loop on arrays - if someone extends Array.prototype (or worse, Object.prototype), then you will not be happy. Use a normal for loop (which also allows you to use the final item easily):
var len = scenes[sceneID].vehicles.length;
for (var vehicleIndex = 0; vehicleIndex < len; vehicleIndex++) {
vehicleID = scenes[sceneID].vehicles[vehicleIndex];
//...
}
//Do something with the final item here
//Similar to this: itemFunc(vehicleID);
See this SO question for more details.

Handling JSON Object Array

I got a realy simple question:
Take a look at this JSON String:
this.objects = [{"pid":"2","x":"10","y":"10"}]; // only one i know
Now i would like to adress an object out of it like so:
this.objects.pid[2]
I know thats pointless in this case as you would access it like:
this.objects[0]
The thing is that i need to adress an object array in JSON by the object id and not the array index. Is there a nice approach to this?
Thanks!
function getObject(id, array) {
for (var i = 0; i < array.length; i++) {
if (array[i].pid == id) {
return array[i]
}
}
}
A function that takes your id and array and returns your object. Basically loop through the array and find the element with your id. This can be optionally cached for speed increase.
It doesn't need to be a single element array, so try this...
this.objects = {"pid":"2", "x":"10", "y":"10"};
And you can read it either of these ways:
this.objects.pid;
this.objects['pid'];
If you wanted multiple lists of x,y,etc. then try something like this:
this.objects = { "2": {"x": "10", "y": "10"} };
this.objects["2"].x;
this.objects["2"]["x"];
Essentially, in this case, just use the "pid" as they key for each object that contains the properties you want for each item.

Categories