我有以下数组:
var my_list = ["XXXS", "XXS", "XS", "S", "M", "L", "XL", "XXL", "XXXL"];
然后我从json获得了以下对象数组:
my_json = [
{
size: "L",
color: "black"
}, {
size: "M",
color: "blue"
}, {
size: "XXL",
color: "red"
}, {
size: "XXS",
color: "red"
}
];
我试图按照size
的顺序排序my_list
对象数组
我发现了排序功能,但它按字母顺序排序,我不知道是否有一种简单的方法可以做到。
这是一个jsfiddle,您可以尝试:http://jsfiddle.net/ew3ZU/3/
要明确:
实际输出
[{"size":"L","color":"black"},{"size":"M","color":"blue"},{"size":"XXL","color":"red"},{"size":"XXS","color":"red"}]
渴望输出
[{"size":"XXS","color":"red"},{"size":"M","color":"blue"}{"size":"L","color":"black"},{"size":"XXL","color":"red"}]
答案 0 :(得分:3)
您可以尝试这样的事情:
//only modern browsers support indexOf method for an array
my_list.indexOf = function(e){
for(var i = 0; i < this.length; i++){
if(this[i] === e) return i;
}
return -1;
};
//the sorter to compare 2 object based on the property size.
function sorter(a,b){
var s1 = my_list.indexOf(a.size);
var s2 = my_list.indexOf(b.size)
return s1 > s2 ? 1 : s1 < s2 ? -1 : 0;
}
my_json.sort(sorter);
答案 1 :(得分:2)
你可以尝试一下:
var ordered_list = [];
for (i = 0; i < my_list.length; i++) {
for (j = 0; j < my_json.length; j++) {
if (my_list[i] == my_json[j].size) {
ordered_list.push(my_json[j]);
}
}
}
答案 2 :(得分:1)
<强> Demo 强> 试试这个
var newMyJson = [];
for (var i = 0; i < my_list.length; i++) {
var value = my_list[i];
$.each(my_json, function (i, val) {
if (value == val.size) {
newMyJson.push(my_json[i]);
return;
}
});
}