How can i loop through the below multidimensional array?
I am creating the array like this:
var _cQueue = [[]];
And adding items like this:
var valueToPush = new Array();
valueToPush['[email protected]'] = '1234567';
_cQueue.push(valueToPush);
I want to loop through all different email adresses that are added, and then each random string associated with that email
Any ideas?
How can i loop through the below multidimensional array?
I am creating the array like this:
var _cQueue = [[]];
And adding items like this:
var valueToPush = new Array();
valueToPush['[email protected]'] = '1234567';
_cQueue.push(valueToPush);
I want to loop through all different email adresses that are added, and then each random string associated with that email
Any ideas?
Share Improve this question asked Mar 20, 2013 at 13:52 AlosyiusAlosyius 9,15126 gold badges78 silver badges121 bronze badges 1- stackoverflow./questions/4909218/… ... see from this answer and you should get it – theshadowmonkey Commented Mar 20, 2013 at 13:56
2 Answers
Reset to default 8First, you should not add elements to arrays by key, but to objects. Which means your global object should be build as :
var _cQueue = [];
var valueToPush = {}; // this isn't an array but a js object used as map
valueToPush['[email protected]'] = '1234567';
_cQueue.push(valueToPush);
Then, you iterate using two kinds of loops :
for (var i=0; i<_cQueue.length; i++) { // iterate on the array
var obj = _cQueue[i];
for (var key in obj) { // iterate on object properties
var value = obj[key];
console.log(value);
}
}
See MDN's excellent Working with objects.
If you want to find the email associated to an id, you can do two things :
1) loop until you find it :
function find(id) {
for (var i=0; i<_cQueue.length; i++) { // iterate on the array
var obj = _cQueue[i];
for (var key in obj) { // iterate on object properties
var value = obj[key];
if (value==id) return key;
}
}
}
2) put all the ids in a map so that it can be found faster :
var bigMap = {};
for (var i=0; i<_cQueue.length; i++) { // iterate on the array
var obj = _cQueue[i];
for (var key in obj) { // iterate on object properties
bigMap[obj[key]] = key; // maps the id to the email
}
}
function find(id) {
return bigMap[id];
}
use for-in to both levels:
for(var val in _cQueue){
var obj = _cQueue[val];
for(var val1 in obj){
alert('key(email):' + val1 + '\nValue:' + obj[val1]);
}
}