Ben*_*nno 5 javascript sorting jquery json object
尝试对JSON对象进行排序时遇到问题.基本上,人们可以按任意随机顺序将产品添加到我们的订单表单中,但它在摘要中显示的顺序需要是我们希望它们如何定位(而不是他们选择它们的顺序),这就是我需要排序的原因'id'(或者我们稍后将按'pos'字段排序)
基本上,我需要按id提升排序.1,2,103而不是2,103,1
我似乎遇到了问题,因为单个对象的索引是数字(或者只是他们在那里的事实......).
我需要按照array.sort(function(a,b){return a.id-b.id})的方式做一些事情; 但我认为这不起作用,因为1,它不是一个数组(它是一个对象),2,它有那些讨厌的索引(我需要代码的另一部分)...
有任何想法吗????
var products = {
"2": {
"id": "2",
"price": "119",
"quantity": "1",
"thumb": "img\/store\/comp-08n.png"
},
"103": {
"id": "103",
"price": "109",
"quantity": "1",
"thumb": "img\/store\/basketballhoop.png"
},
"1": {
"id": "1",
"price": "309",
"quantity": "1",
"thumb": "img\/store\/comp-08.png"
}
};
Run Code Online (Sandbox Code Playgroud)
您的订单中需要多少件商品?您可以安全地在Javascript阵列中对10'000个项目进行排序,而不会出现太多速度问题.为什么不使用真正的阵列呢?
你甚至可以为它注入自定义属性,大致类似于
var products = [...];
products.findById = function(id) {
for (var i=0, len=this.length; i<len; i++) {
if (id == this[i].id) return this[i];
}
return null;
};
alert( products.findById(103).price ); // -> 119
Run Code Online (Sandbox Code Playgroud)
并添加预定义的分拣机
products.sortById = function() {
this.sort(function(a,b) {
return a.id - b.id;
});
};
products.sortById(); // sort array by product id
Run Code Online (Sandbox Code Playgroud)
**编辑**
在你的PHP方面,你可能有类似的东西:
$products = array(
2 => array( 'id' => 2, ... ),
103 => array( 'id' => 103, ... ),
1 => array( 'id' => 1, ... ),
);
// get a JSON array
$jsonArray = json_encode(array_values($products));
Run Code Online (Sandbox Code Playgroud)
将返回您需要的东西.
**注意**
在阵列中添加新项时,不应显式设置索引.使用数组的push功能,如
products.push({id:123, price:200.49, quantity:1, thumb:'/path/to/file'});
Run Code Online (Sandbox Code Playgroud)
删除项目有点棘手,但是,类似于:
products.removeById = function(id) {
for (var i=0, len=this.length; i<len; i++) {
if (id == this[i].id) return this.splice(i, 1)[0];
}
return null;
};
products.removeById(123); // -> returns the removed element! or null if nothing was removed
Run Code Online (Sandbox Code Playgroud)
请参阅此处的演示(使用Chrome开发工具进行控制台输出).