I have a code similar to this (rendering info开发者_JAVA技巧rmation from external service):
var myList = {'id1' : {prop1:'v1', prop2:'v2'},
'id2' : {prop1:'v3', prop2:'v4'}};
for (var k in myList) {
var html = '<div id="xxx">stuff</div>';
html.data('item', myList[k]);
$('#parentDiv').append(html);
}
As I can't rely on ordering when using for (x in y)
I want to insert the elements in a specific position, let's say ordered by prop1
.
So, how can I change the append to an insert after the element whose prop1
is immediately lesser than the actual element being inserted?
How about use an array:
var myList = {'id1' : {prop1:'v1', prop2:'v2'},
'id2' : {prop1:'v30', prop2:'v4'},
'id3' : {prop1:'v13', prop2:'v4'}},
sorted = [];
for (var k in myList) {
sorted.push(myList[k]);
}
sorted.sort(function (a,b) {
return a.prop1 > b.prop1;
});
for (var i = 0; i < sorted.length; i++) {
var html = '<div id="xxx">stuff</div>';
html.data('item', sorted[i]);
$('#parentDiv').append(html);
}
You may need to sort them first?
tmpList = [] // turn myList to array
tmpList.sort(function (a, b) { return a.prop1 > b.prop1});
// turn tmpList to dict
精彩评论