Reputation: 1799
I have an object that i am trying to loop through with foreach, but i am failing (this is what 6 months of not coding does to me...)
This works just fine:
<div data-bind="text: $root[36].partition"></div>
But the foreach not working for me.
<div data-bind="foreach: $root">
<div data-bind="text: $data.partition"></div>
</div>
All I get in my html is this:
<div data-bind="foreach: $root"></div>
My viewModel is getting JSON data from php script and its structured like this: 09, 10 and 36 are partition IDs. Each partition has a 'partition' variable, which displays the name of the partition. Actual JSON structure goes deeper and this is here just for representation
top level
09
partition
vip
10
partition
vip
36
partition
vip
This is my JS. Nothing special, I am just playing around
$(document).ready(function() {
var viewModel = {};
$.getJSON('/lbstat/read.php', function(data) {
viewModel = ko.mapping.fromJS(data);
ko.applyBindings(viewModel);
});
});
JSON:
{"23":{
"partition":"Prod New SVCs Partition",
"env_dc":"Prod",
"hosts":["server01.domain.com", "server02.domain.com"],
"vips":{
"124":{
"dc_endpoint":"ADX - Prod - Intranet",
"gw_port":"9007",
"vip_name":"adx-prd.domain.net"
},
"210":{
"dc_endpoint":"Msg - Prod - Internet",
"gw_port":"8013",
"vip_name":"messaging-prd.domain.com"
},
"211":{
"dc_endpoint":"Msg - Prod - Intranet",
"gw_port":"9013",
"vip_name":"messaging-prd.domain.net"}
},
}
}
Complete JSON available here: http://pastebin.com/zpNngr53
What am I doing wrong here?
Upvotes: 3
Views: 482
Reputation: 19847
You can't foreach
an object. You can only foreach
an array. The JSON you posted is an object with a bunch of numbered properties, which is why $root[36]
works, because 36
is the name of a property on the object, not the index of an array.
If your object was an array your code would work.
Upvotes: 4