Reputation: 392
I am iterating through a json object of nested objects using nested $.each functions. The problem is that as I loop through the nested object with the inner $.each it returns the keys for all the nested objects, not just the first nested object. On the second iteration it returns all the keys less the keys of the first nested object, and so on. Here is the code:
var data = {
'1': {
'a': '1a',
'b': '1b',
'c': '1c'
},
'2': {
'a': '2a',
'b': '2b',
'c': '2c'
},
'3': {
'a': '3a',
'b': '3b',
'c': '3c'
}
};
var my_ul = $('#mydiv ul');
$.each(data, function(key, value) {
$('<li>', {
html: key + '<ul></ul>'
}).appendTo(my_ul);
var deep_ul = $('#mydiv ul li ul');
$.each(value, function(k, v) {
$('<li>', {
html: k + ':' + v
}).appendTo(deep_ul);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mydiv">
<ul></ul>
</div>
<div id="test"></div>
Here is the result: http://jsfiddle.net/TsJP5/82/
What am I doing wrong. I expect it to give
- 1 +a : a1
+b : b1
+c : c1
- 2 +a : a2
+b : b2
+c : c2
and so on...
Upvotes: 2
Views: 78
Reputation: 16355
It's all in your jQuery DOM manipulation. The selector #mydiv ul li ul
is pulling EVERY decendent ul node in #mydiv.
Instead, I find it's cleanest just build out each li and decendent ul individually and append them to the parent node:
var data = {
'1':{
'a':'1a',
'b':'1b',
'c':'1c'
},
'2':{
'a':'2a',
'b':'2b',
'c':'2c'
},
'3':{
'a':'3a',
'b':'3b',
'c':'3c'
}
};
var my_ul = $('#mydiv ul');
$.each(data, function(key, value){
var li = $('<li>', {html:key});
var deep_ul = $('<ul></ul>');
$.each(value, function(k, v){
$('<li>', {html:k + ':' + v}).appendTo(deep_ul);
});
deep_ul.appendTo(li)
li.appendTo(my_ul);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mydiv">
<ul>
</ul>
</div>
<div id="test">
</div>
Upvotes: 2