添加两个json对象并进行排序

时间:2012-01-15 10:49:48

标签: javascript json

我有三个类似的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分类为价格指数。

任何提示都将受到赞赏。 谢谢:))

3 个答案:

答案 0 :(得分:2)

如果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;降序排列。 jsfiddle:http://jsfiddle.net/diode/FzzHz/

答案 1 :(得分:1)

将它们转换为对象,this应该做到这一点

答案 2 :(得分:1)

您可以使用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);