I have an array, clientList
:
[
[
clientID: "123"
data: "data1"
]
[
clientID: "456"
data: "data2"
]
[
clientID: "789"
data: "data3"
]
]
I'm trying to iterate over all 3 arrays, displaying all keys and values for each.
I iterate over the individual arrays by doing the standard $.each(clientList, function() {}
.
Now I'm trying to iterate over a single array using $.each($(this), function(key, value) {}
but the key is just the index in number form, not the key name as a string. Is there any way to do this?
I found Iterating an associative array with jQuery .each as a possible starting point, but there's no way to initialize $(this)
to {}
, is there?
I have an array, clientList
:
[
[
clientID: "123"
data: "data1"
]
[
clientID: "456"
data: "data2"
]
[
clientID: "789"
data: "data3"
]
]
I'm trying to iterate over all 3 arrays, displaying all keys and values for each.
I iterate over the individual arrays by doing the standard $.each(clientList, function() {}
.
Now I'm trying to iterate over a single array using $.each($(this), function(key, value) {}
but the key is just the index in number form, not the key name as a string. Is there any way to do this?
I found Iterating an associative array with jQuery .each as a possible starting point, but there's no way to initialize $(this)
to {}
, is there?
4 Answers
Reset to default 12What's wrong with plain JavaScript? You can use Object.keys
and Array.prototype.forEach
to go through the keys and values on an object.
// Loops through every single client in the client list.
clientList.forEach(function (client) {
// Logs each of the key-value pairs on the client object.
Object.keys(client).forEach(function (key) {
console.log(key + ': ' + client[key]);
});
});
There are syntactical errors in your array, I hope that is a copy mistake if so then
var clientList = [{
clientID: "123",
data: "data1"
}, {
clientID: "456",
data: "data1"
}, {
clientID: "789",
data: "data1"
}]
$.each(clientList, function (idx, obj) {
$.each(this, function(key, val){ //you can use `this` or `obj` to iterate over
console.log(key, val)
})
})
Demo: Fiddle
Inside the each()
callback this
refers to a javascript object, so you should not try to create a jQuery wrapper around it using $(this)
while passing to the second each()
call.
You need something like this:
var clientList = [
{
clientID: "123",
data: "data1"
},
{
clientID: "456",
data: "data1"
},
{
clientID: "789",
data: "data1"
}
];
$(document).ready(function(){
var output = $('#output');
$.each(clientList, function(index, obj){
output.append('<div>Item ' + index + '</div>');
$.each(obj, function(key, value){
output.append('<div>' + key + ' = ' + value + '</div>');
});
output.append('<br />');
});
});
http://jsfiddle.net/4JcjR/
If you just want to print them out in a debugger try Object.entries(yourAssociativeArray)
console.log(JSON.stringify(clientList))
to get the correct string representation of the object – Arun P Johny Commented Nov 20, 2013 at 2:39