Javascript/jQuery: Loop through array values inside an object - javascript

var myJSON =
{"data":
[{"obj1":"value1",
"obj2":"value2"},
{"obj1":"value3",
"obj2":"value4"},
{"obj1":"value5",
"obj2":"value6"}]
};
I've got an array looking like one above. I'd like to loop through each obj2 and get the values. How can this be done in Javascript/jQuery?
I tried using:
for (var i = 0; i < myJSON.data.length; i++) {
console.log(i.obj2);
}
but it looks as though myJSON.data doesn't return a length...

i is only an iterator you can use to access the array
for (var i = 0; i < myJSON.data.length; i++) {
console.log(myJSON.data[i].obj2);
}

for (var i = 0; i < myJSON.data.length; i++) {
console.log(myJSON.data[i].obj2);
}

The problem is that you're trying to access the obj2 key from your i variable, which isn't your array. Try this way:
for (var i = 0; i < myJSON.data.length; i++) {
console.log(myJSON.data[i].obj2);
}
Other ways to do the same:
for(var i in d=myJSON.data){
console.log(d[i].obj2);
}
or
myJSON.data.forEach(function(a){
console.log(a.obj2)
})

Related

Access array outside for loop

I want to access array variable outside the loop. but its returning null. below is sample code.
var result = [];
for (var i=0; i < 10; i++) {
result.push[i];
}
The syntex of push method is push() not push[].
var result = [];
for (var i=0; i < 10; i++) {
result.push(i);
}
console.log(result);
For more info about push() look How to append something to an array?
push is a method implemented on array. The basic syntax of invoking or calling a function is to specify parenthesis () after the function name.
Array.prototype.push()
The push() method adds one or more elements to the end of an array and returns the new length of the array.
var result = [];
for (var i=0; i < 10; i++) {
result.push(i);
}
console.log(result);
Please use the below code:
var result = [];
for (var i=0; i < 10; i++) {
result.push(i);
}
You can do that like this also.
var result = [];
for (var i=0; i < 10; i++) {
result[i]=i;
}
If you want to use push then use like this result.push(i)

How to loop through Nested Json Array with (JavaScript) for loop and display the text

This may be a fairly simple question but it's just not working for me no matter how many times I change the for loop around. So how would you loop through this array using a for loop in JavaScript?
var fielditems =[
[["News Tips"],["Opinions"],["MedMinutes"]],
[["Yes"],["No"],["Maybe"]],
[["How"],["Why"],["When"]]
];
This is what I have and it's not working. I used an alert to just test out the result but it's not even returning anything.
for(itemSet in fielditems){
var itemSetValues = fielditems[itemSet];
for(set in itemSetValues){
var itemValue = itemSetValues[set];
for(value in itemvalue){
alert(itemValue[value]);
}
}
}
What am I doing wrong?
Don't use for() with in for arrays. It's for object properties. Use the standard format instead.
Demo: http://jsfiddle.net/ThinkingStiff/EVWch/
Script:
var fielditems =[
[["News Tips"],["Opinions"],["MedMinutes"]],
[["Yes"],["No"],["Maybe"]],
[["How"],["Why"],["When"]]
];
for( var itemIndex = 0; itemIndex < fielditems.length; itemIndex++ ){
var itemSetValues = fielditems[itemIndex];
for(var setIndex = 0; setIndex < itemSetValues.length; setIndex++ ){
var itemValue = itemSetValues[setIndex];
for(var valueIndex = 0; valueIndex < itemValue.length; valueIndex++ ){
alert(itemValue[valueIndex]);
};
};
};
​
Firstly, console is your friend. You get error ReferenceError: itemvalue is not defined because javascript is case sensitive. Change itemvalue in the most nested loop to itemValue.
Secondly, if you want iterate thorugh an array, you should use for-loop instead for-in-loop
Don't use for-in loops on arrays
Don't use (running) variables without declaring them as local
for (var i=0; i<fielditems.length; i++) {
var itemSetValues = fielditems[i];
for (var j=0; j<itemSetValues.length; j++) {
var itemvalue = itemSetValues[j]; // notice the case
for (var k=0; k<itemvalue.length; k++) {
alert(itemvalue[k]);
}
}
}
for..in is for objects ({}), not for arrays ([]).
You need to use a standard for loop.
for(var i = 0, iLen = fielditems.length; i < iLen; i++){
var iItem = fielditems[i];
for(var j = 0, jLen = iItem.length; j < jLen; j++){
var jItem = iItem[j];
alert(jItem[0]); // you can also add another loop here, if this will have more elements
}
}
NOTE:
for(var i = 0, iLen = fielditems.length; i < iLen; i++)
is better than:
for(var i = 0; i < fielditems.length; i++)
because fielditems.length isn't requested each loop, just once at the start.

Using .set on a filtered array of IDs in backbone

I used Underscore.js's _.filter to get an array of object ids like so:
var downstreamMeters = _.filter(that.collection.models, function(item) { return item.get("isdownstreammeter"); });
Now I want to set a certain attribute of each model in the array. I thought it would make sense to do this:
for (var i = 0; i < downstreamMeters.length; i++) {
var sum = 0;
inputMeters = downstreamMeters[i].get("inputmeters");
for (var i = 0; i < inputMeters.length; i++) {
var flow = parseFloat(that.collection.get(inputMeters[i]).get("adjustedflow"));
sum += flow;
}
downstreamMeters[i].set({incrementalflow: sum});
}
However, I get the error:
Uncaught TypeError: Cannot call method 'set' of undefined
I checked the downstreamMeters array and it has the right objects in it. What do I need to do to set the attribute for each model in the array?
Saying for(var i = 0; ...) is somewhat misleading. JavaScript hoists all var declarations up to the top of the closest scope and for loop doesn't create its own scope. The result is that this:
for (var i = 0; i < downstreamMeters.length; i++) {
var sum = 0;
inputMeters = downstreamMeters[i].get("inputmeters");
for (var i = 0; i < inputMeters.length; i++) {
var flow = parseFloat(that.collection.get(inputMeters[i]).get("adjustedflow"));
sum += flow;
}
downstreamMeters[i].set({incrementalflow: sum});
}
is the same as this:
var i, sum, flow;
for (i = 0; i < downstreamMeters.length; i++) {
sum = 0;
inputMeters = downstreamMeters[i].get("inputmeters");
for (i = 0; i < inputMeters.length; i++) {
flow = parseFloat(that.collection.get(inputMeters[i]).get("adjustedflow"));
sum += flow;
}
downstreamMeters[i].set({incrementalflow: sum});
}
Now you can see that you are using exactly the same i in the outer and inner loops. On the first run through the loop, i will be inputMeters.length when you say downstreamMeters[i].set(...). Apparently, inputMeters.length > downstreamMeters.length so you end up running off the end of downstreamMeters; if you try to access an element of an array that is past the array's end, you get undefined and there's your
Cannot call method 'set' of undefined.
error.
Nesting loops is fine but you should be using different variables:
var i, j, sum, inputMeters;
for (i = 0; i < downstreamMeters.length; i++) {
sum = 0;
inputMeters = downstreamMeters[i].get("inputmeters");
for (j = 0; j < inputMeters.length; j++)
sum += parseFloat(that.collection.get(inputMeters[j]).get("adjustedflow"));
downstreamMeters[i].set({incrementalflow: sum});
}

How can I iterate over all unique pairs of entries in an object?

I currently have an array data structure that I iterate over like this, calling foo on each unique pair of elements.
for(var i = 0; i < arr.length; i++) {
for(var j = i + 1; j < arr.length; j++) {
foo(arr[i], arr[j]);
}
}
However, I've realized that I'd rather use an object instead of an array, since I can then add and remove elements by name very easily.
However, I can't see an obvious way to iterate over such an object. The closest I can get is:
for(i in obj) {
for(j in obj) {
foo(obj[i], obj[j]);
}
}
Obviously, this will do each pair twice, and even produce a pair of identical elements. Is there an easy way to iterate over an object in the same way as I do in the array in my first code sample?
Update:
Performance testing the solutions on jsperf.
My solution that was at first written as a comment:
Add an if (i < j) condition in the inner loop. It might not be the best solution, but it would work as long as the foo function does the same thing for foo(2, 10) and foo(10, 2):
for(i in obj) {
for(j in obj) {
if (i < j) {
foo(obj[i], obj[j]);
}
}
}
Assuming I understand your question... maybe check to see if the value has already been visited by the outer loop?
var visited = {}
for(i in obj) {
visited[i] = true;
for(j in obj) {
if(j in visited){ continue; }
foo(obj[i], obj[j]);
}
}
Use Object.keys() to get the list of keys out as an array:
keys = Object.keys();
for(i=0;i<keys.length;i++) {
for(j=i+1;j<keys.length;j++) {
foo(obj[keys[i]], obj[keys[j]]);
}
}
Maybe You can try unset used objects:
for(i in obj) {
var a = obj[i];
delete obj[i];
for(j in obj) {
foo(a, obj[j]);
}
}
http://jsfiddle.net/bXcvb/
If you need to original obj in tact see: How do I correctly clone a JavaScript object?
You can push the object keys into an array:
var obj_keys = [];
for (i in obj) {
obj_keys.push(i);
}
for(i = 0; i < obj_keys.length; ++i) {
for(j = i + 1; j < obj_keys.length; ++j) {
foo(obj[obj_keys[i]], obj[obj_keys[j]]);
}
}

Handling multidimentional array in java script is not working

function split(str)
{
var array = str.split(';');
var test[][] = new Array();
for(var i = 0; i < array.length; i++)
{
var arr = array[i].split(',');
for(var j = 0; j < arr.length; j++)
{
test[i][j]=arr[j];
}
}
}
onchange="split('1,2,3;4,5,6;7,8,9;a,b,c;d,e,f;g,h,i')"
it was not working. i need to split this string to 6*3 multi dimentional array
var array[][] = new Array() is not valid syntax for declaring arrays. Javascript arrays are one dimensional leaving you to nest them. Which means you need to insert a new array into each slot yourself before you can start appending to it.
Like this: http://jsfiddle.net/Squeegy/ShWGB/
function split(str) {
var lines = str.split(';');
var test = [];
for(var i = 0; i < lines.length; i++) {
if (typeof test[i] === 'undefined') {
test[i] = [];
}
var line = lines[i].split(',');
for(var j = 0; j < line.length; j++) {
test[i][j] = line[j];
}
}
return test;
}
console.log(split('a,b,c;d,e,f'));
var test[][] is an invalid javascript syntax.
To create a 2D array, which is an array of array, just declare your array and push arrays into it.
Something like this:
var myArr = new Array(10);
for (var i = 0; i < 10; i++) {
myArr[i] = new Array(20);
}
I'll let you apply this to your problem. Also, I don't like the name of your function, try to use something different from the standards, to avoid confusion when you read your code days or months from now.
function split(str)
{
var array = str.split(';'),
length = array.length;
for (var i = 0; i < length; i++) array[i] = array[i].split(',');
return array;
}
Here's the fiddle: http://jsfiddle.net/AbXNk/
var str='1,2,3;4,5,6;7,8,9;a,b,c;d,e,f;g,h,i';
var arr=str.split(";");
for(var i=0;i<arr.length;i++)arr[i]=arr[i].split(",");
Now arr is an array with 6 elements and each element contain array with 3 elements.
Accessing element:
alert(arr[4][2]); // letter "f" displayed

Categories

Resources