Reputation: 9121
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?
Upvotes: 1
Views: 10386
Reputation: 382130
First, 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];
}
Upvotes: 8
Reputation: 5253
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]);
}
}
Upvotes: -1