javascript 排序 JSON 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6147547/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sorting JSON Object
提问by Benno
Having a problem trying to sort a JSON object. Basically, people can add products in any random order to our order form, but the order it shows in the summary needs to be how we want them to be positioned (not the order they select them), so thats why I need to sort by 'id' (or we'll sort by a 'pos' field later)
尝试对 JSON 对象进行排序时遇到问题。基本上,人们可以以任何随机顺序将产品添加到我们的订单中,但它在摘要中显示的顺序需要是我们希望它们如何定位(而不是他们选择它们的顺序),所以这就是为什么我需要排序'id'(或者我们稍后会按 'pos' 字段排序)
Essentially, I need to sort by the id ascending. 1,2,103 instead of 2,103,1
本质上,我需要按 id 升序排序。1,2,103 而不是 2,103,1
I seem to be having issues because the index into the individual objects are numbers (or just the fact that they're there...).
我似乎遇到了问题,因为单个对象的索引是数字(或者只是它们在那里的事实......)。
I need to do something along the lines of array.sort(function(a,b){ return a.id-b.id }); but I'm presuming that doesn't work because 1, its not an array (its an object), and 2, it has those pesky indexes (that i need for another part of my code)...
我需要按照 array.sort(function(a,b){ return a.id-b.id }); 但我认为这不起作用,因为 1,它不是数组(它是一个对象),2,它有那些讨厌的索引(我的代码的另一部分需要这些索引)...
Any ideas????
有任何想法吗????
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"
}
};
采纳答案by Yanick Rochon
How many items do you need in your orders? You can safely sort 10'000 items in a Javascript array without much of speed issues. Why don't you work with a real array instead?
您的订单需要多少件商品?您可以安全地对 Javascript 数组中的 10'000 个项目进行排序,而不会出现太多速度问题。为什么不使用真正的数组呢?
You could even inject custom properties to it, roughly something like
您甚至可以向其注入自定义属性,大致类似于
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
and add predefined sorters like
并添加预定义的分拣机,例如
products.sortById = function() {
this.sort(function(a,b) {
return a.id - b.id;
});
};
products.sortById(); // sort array by product id
** EDIT**
**编辑**
On your PHP side, you might have something like :
在您的 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));
will return what you need.
将返回您需要的东西。
** NOTE**
**注意**
You should not explicitly set indexes when adding new items in your array. Use the array's push
function, like
在数组中添加新项目时,不应显式设置索引。使用数组的push
函数,比如
products.push({id:123, price:200.49, quantity:1, thumb:'/path/to/file'});
Removing an item is a bit tricky, however, something like :
但是,删除项目有点棘手,例如:
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
See demo here(use Chrome developper tools for console output).
请参阅此处的演示(使用 Chrome 开发人员工具进行控制台输出)。
回答by c-smile
There are two types of collections in JavaScript and in JSON:
JavaScript 和 JSON 中有两种类型的集合:
- key/value map (object) - unordered collection and
- Array - index/value map (array) - ordered collection.
- 键/值映射(对象) - 无序集合和
- 数组 - 索引/值映射(数组) - 有序集合。
By definition only array can be sorted. Use array.
根据定义,只能对数组进行排序。使用数组。
回答by googamanga
recursive solution, doesn't deal with arrays though, javascript
递归解决方案,虽然不处理数组,javascript
var alphabetizeJSON = function(obj){
var key,
array = [],
stringifiedValuesObj = {},
jsonKeyVal = "",
i,
keyName;
for (key in obj) {
if (typeof obj[key] === "object"){
stringifiedValuesObj[key] = "" + alphabetizeJSON(obj[key]);
} else {
obj[key] = obj[key].replace(/\"/gi,'\\"');
}
array.push(key);
}
array.sort();
for (i = 0; i < array.length; i++){
keyName = array[i];
jsonKeyVal += '"' + keyName + '": ';
jsonKeyVal += stringifiedValuesObj[keyName] ? stringifiedValuesObj[keyName] : '"' + obj[keyName] + '"';
if (i < array.length - 1 ) {
jsonKeyVal += ',';
}
}
return '{ ' + jsonKeyVal + '}';
};
回答by dee-see
Check out JSONArray
s. They might be what you need. http://json.org/java/
检查JSONArray
s。它们可能正是您所需要的。http://json.org/java/
回答by Tamzin Blake
Indeed, you should be able to use an array instead of an object for this job, and that will solve a lot of your difficulty.
实际上,您应该能够在这项工作中使用数组而不是对象,这将解决您的很多困难。
If you can't do that, you can convert the object into an array to give it ordering... something like this:
如果你不能这样做,你可以将对象转换成一个数组来给它排序......像这样:
var a = []
for (var p in obj) {
a[+p] = obj[p]
}
If you can't do that, you could dynamically add the information to the page in the order you want (the following is a bad idea)...
如果你不能这样做,你可以按照你想要的顺序动态地将信息添加到页面中(以下是一个坏主意)......
for (var i = 0; i < 10000; i++) {
if (obj[i] !== undefined) {
add_to_page(obj[i]) //define this somewhere
}
}