我有三个类似的json对象。现在,我希望加入整个列表,然后根据索引之一对完整的列表进行排序。在这里,对象描述
对象1
[{"link":"#","prod":"Fundamentals Of Software Engineering","price":" Rs. 200 "},{"link":"##","prod":"Real-Time Systems: Theory And Practice","price":" Rs. 394 "}]对象2
[{"link":"#","prod":"Fundamentals Of Software Engineering","price":" Rs. 200 "},{"link":"##","prod":"Real-Time Systems: Theory And Practice","price":" Rs. 394 "}] 对象3
[{"link":"#","prod":"Fundamentals Of Software Engineering","price":" Rs. 200 "},{"link":"##","prod":"Real-Time Systems: Theory And Practice","price":" Rs. 394 "}] 一旦我加入其中,我希望将完整的数组(新的) w.r.t排序到价格指数。
如有任何提示,我们将不胜感激。谢谢:)
发布于 2012-01-15 11:26:48
如果Object1、Object2和Object3是JSON字符串,则使用eval函数将其转换为Javascript对象。
然后使用concat方法合并它们。http://www.w3schools.com/jsref/jsref_concat_array.asp
var mergedArray = arr1.concat(arr2, arr3);然后在Javascript中使用sort方法进行排序。参考文献:http://www.w3schools.com/jsref/jsref_sort.asp参考:https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort
var sorted = mergedArray.sort(function(a, b){
// This function is used by sort method for sorting process
// This function gets called with parameters a,b which are the elements in array (here product objects from your JSON)
// if this function returns value < 0 a is placed before b
// if this function returns 0 nothing is changed
// if this function returns value > 0 b is placed before a
// a.price.replace("Rs.", "") removes Rs. from price string. so "Rs. 200" becomes 200
// parseFloat(a.price.replace("Rs.", "")) makes it number. "200" becomes 200. "200.50" becomes 200.5
// priceA - priceB returns -ve value if priceA < priceB, 0 if priceA = priceB, +ve value if priceA > priceB.
var priceA = parseFloat(a.price.replace("Rs.", ""));
var priceB = parseFloat(b.price.replace("Rs.", ""));
return priceA - priceB;
});使用return priceB - priceA;进行降序。小提琴手:http://jsfiddle.net/diode/FzzHz/
。
发布于 2012-01-15 10:53:15
将它们转换为object,this应该能做到这一点
发布于 2012-01-15 10:55:19
可以使用concat方法连接数组:
var result = arr1.concat(arr2, arr3);然后,您可以对结果数组进行排序。
让我们编写使用prod属性对它们进行排序的排序函数(您可以根据您希望的任何属性对它们进行排序):
function SortByProd(a, b) {
var aProd = a.prod.toLowerCase();
var bProd = b.prod.toLowerCase();
return ((aProd < bProd) ? -1 : ((aProd > bProd) ? 1 : 0));
}然后分类:
result.sort(SortByProd);https://stackoverflow.com/questions/8869123
复制相似问题