Stupid questions, iterating over JSON [duplicate] - javascript

This question already has answers here:
Iterate through object properties
(31 answers)
Closed 6 years ago.
So a two part question, because I can't solve the first problem, and the hacky work around isn't seeming to work either.
I have a JSON object, and within that object is nested object. I want to manipulate something within a deep layer array.
So to start with, I need to learn how to iterate over keys in an object, but I can't see how you do it.
Say I have an object with objects within it, how do I iterate over these?
If it were an array I would do
for (i = 0; i < arrayLength; i++)
{console.log(array[i])}
But, because they're words, I can't just i++, so I made an array of the words, then wanted to do the same as above, but
for (i = 0; i < arrayLength; i++)
{console.log(jsonObject.array[i]}
, but this isnt seeming to work, I just get undefined returned.
Apologies for the poor explaination.

There is a method to get the keys and then you can iterate with those.
var keys = Object.keys(obj);
for(i = 0 ; i < keys.length; i++){
var result = obj[keys[i]];
console.log(result);
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

You need to use a 'for..in' loop, or, even better, Object.keys() handles this well.
Object.keys() documentation here.
for (var i in myObject) { console.log[i] };

You iterate using for (key in obj) {...} syntax.
As in:
var t = document.getElementById('myTextField');
var obj = {name:'John',last:'Doe'};
var result = '';
for (key in obj) {
result += key + '=' + obj[key] + ',';
}

Related

JS - Iterating objects in for loop

I can't seem to figure out this problem. I need to iterate over some objects, as of right now, named column_1, column_2, column_3 and column_4.
How do i use the i variable, to get the correct object?
This is my code right now, which isn't working...
for (var i = 1; i < layouts.columns; i++) {
console.log(layouts.column_[i]);
}
Do you mean you need to iterate over the properties of an object?
It's not like an array. You have to do something like
let keys = Object.keys(layouts.columns);
for(var i = 0; i < keys.length -1; i ++ ) {// do stuff};
or
for (var key in layouts.columns) {
var column = layouts.columns[key];
}
Or like others have mentioned, if all property names are column_x, you could loop through 4, and access like layouts['column_'+i]

Using 2 arrays of objects, iterate over them using something similar to IndexOf (or other option)

I have an array of objects, i was trying to iterate over. The array is pretty simple in format.
{a:5, b:"key", c:19}
i was trying to compare an array with a subset, say: [{a:5},...]
for (var i = 0; i < subset.length; i++) {
var searchTerm = subset[i].a;
var index = objs.indexOf(searchTerm, function (el) {
return el.a;
});
if (index > -1) {
objs[index].Found = true;
}
}
So that way ultimately objs, could have a new key in it, 'Found'
This way, it will set the main array objs item.Found = true, if it existed in subset.
There are 2 issues though. Accounting for multiple instances of the same item, and the fact that this current implementation doesnt seem to work.
This is a slight expansion of (indexOf method in an object array? )but with an array of search terms.
ideally, i dont want to change the arrays at all, so im trying not to slice, etc.
In a lot of the defintions, indexOf is defined as:
function indexOf (key, start);
instead of the ideas i am trying to work with.
Edit
Here is some code that i have to get this working, but i was thinking there is a more effecient way to do it than written.
for (var j = 0; j < compare.length; j++){
var searchTerm = compare[j]["a"];
for (var k = 0; k < objs.length; k++){
if (!objs[k].Found && objs[k]["a"] == searchTerm){
objs[k].Found = true;
break;
}
}
}

Get the length of an array within a JSON object

I want to find out how many items are in my JSON object. I have seen many answers but they all deal with a common value to loop through. I am wanting the results to tell me that there are 2 items in this object. Any help would be great!
[{"manager_first_name":"jim","manager_last_name":"gaffigan"}]
You could use Object.keys in newer browsers. It would return an array of all the keys in the object, and that array would have a length property that will tell you how many items there are in the object :
var arr = [{"manager_first_name":"jim","manager_last_name":"gaffigan"}];
var length = Object.keys(arr[0]).length;
FIDDLE
In non-supporting browsers, you have to iterate
var arr = [{"manager_first_name":"jim","manager_last_name":"gaffigan"}];
var i = 0;
for (var key in arr[0]) i++;
FIDDLE
You can do this:
var arr = [{"manager_first_name":"jim","manager_last_name":"gaffigan"}],
length = 0,
obj = arr[0]; // Get first obj from array
for(var k in obj){
if( obj.hasOwnProperty(k) ) {
length++;
}
}
console.log(length); // Shows 2
You should use hasOwnProperty because you can also extend an Object with functions, there could otherwise also be count als keys.
Links:
hasOwnProperty
Try
var jsonArr = [{"manager_first_name":"jim","manager_last_name":"gaffigan"}];
var itemCount = JSON.stringify(jsonArr).split('":"').length - 1;
This is, of course, a rather coarse(and unreliable) way of doing it, but if you just want the item count, this should work like a charm.

Javascript for loop var "i" is treated as a string?

I am using Titanium to build some mobile apps and I noticed that this will give a result that I wasn't expecting.
data = ['a','b', 'c','d'];
for (var i in data){
Ti.API.debug(i+1);
};
This will print: 01,11,12,13
Is this something particular to Titanium or is it generally in Javascript?
Why isn't 'i' being treated as an integer? I am very confused.
Thanks for your help.
This doesn't directly answer your question, but if you are looping through an array you should not use for (var i in data). This loops through all members of an object, including methods, properties, etc.
What you want to do is this:
for (var i=0, item; i<data.length; i++) {
item = data[i];
}
data is an array, so you use a for loop, not a for-in loop:
var data = [ ... ];
var i;
for ( i = 0; i < data.length; i += 1 ) {
Ti.API.debug( i + 1 );
}
Alternatively, you can use the forEach array method:
data.forEach( function ( val, i ) {
Ti.API.debug( i + 1 );
});
The reason why you see this behavior is that the type of i when using a for-in over an array is string not int. Hence the + is doing string concatenation and not addition. If you want it to be the numerical value then use a for loop
for (var i = 0; i < data.length; i++) {
Ti.API.debug(i + 1);
}
Try this:
data = ['a','b', 'c','d'];
for (var i in data){
Ti.API.debug(i*1+1);
};
Multiplying i x 1 will force it to recognize it as numeric.
Try this:
Ti.API.debug(parseInt(i)+1);
You can do
data = ['a','b', 'c','d'];
for (var i in data){
console.log(parseInt(i)+1);
};
But it is not recommended. Because in Javascript for..in loop is for key:value pairs (Objects). So if use it with an array each index is converted to string as key.
so always use for(i = 0; i < length; i++) with arrays.
This is because javascript handles for-each loop this way.
In other languages for(i in datas) will loop through each data.
But in javascript the i will have index value instead of data. so you have to get data by datas[i].

Loop through associative array in reverse

I'm using a javascript associative array (arr) and am using this method to loop through it.
for(var i in arr) {
var value = arr[i];
alert(i =") "+ value);
}
The problem is that the order of the items is important to me, and it needs to loop through from last to first, rather than first to last as it currently does.
Is there a way to do this?
Four things:
JavaScript has arrays (integer-indexed [see comments below]) and objects (string-indexed). What you would call an associative array in another language is called an object in JS.
You shouldn't use for in to loop through a JS array.
If you're looping through an object, use: hasOwnProperty.
JavaScript doesn't guarantee the order of keys in an object. If you care about order, use an array instead.
If you're using a normal array, do this:
for (var i = arr.length - 1; i >= 0; i--) {
//do something with arr[i]
}
Warning: this answer is ancient.
If you're here for a quick fix, kindly refer to the much better answer below.
Original answer retained, because reasons. See comments.
Using a temporary array holding the keys in reverse order:
var keys = new Array();
for (var k in arr) {
keys.unshift(k);
}
for (var c = keys.length, n = 0; n < c; n++) {
alert(arr[keys[n]]);
}
For a normal array, I would have done this:
var i = arr.length;
while (i--) {
var value = arr[i];
alert(i =") "+ value);
}
This is faster than a "for" loop.
http://blogs.oracle.com/greimer/entry/best_way_to_code_a
In modern browsers you can now use Object.keys to get your array of properties and step through it in reverse order, allowing you to skip the preliminary key collection loop.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
var keys = Object.keys(subject);
for (var i = keys.length-1; i >= 0; i--) {
var k = keys[i],
v = subject[k];
console.log(k+":",v);
}

Categories

Resources