添加两个json对象并进行排序 [英] Adding two json objects and sorting
问题描述
我有三个类似的json对象。现在我希望加入整个列表,然后根据索引之一对完整列表进行排序。在这里,去对象描述
I have got three similar json objects. Now i wish to join the entire list and then sort the complete list according to one of the index. Here, goes the objects description
对象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 "}]
有一次,我加入所有这些,我希望将整个数组(新的)排序到价格指数。
Once, I join all of them , I wish to sort the complete array (new one) w.r.t to price index.
任何提示都将不胜感激。
谢谢:)
Any hint for this will be appreciated. thanks :)
推荐答案
如果Object1,Object2和Object3是JSON字符串,则使用<$ c将其转换为Javascript对象$ c> eval function。
if Object1 , Object2 and Object3 are JSON strings convert it to Javascript objects using eval
function.
然后使用 concat
方法合并它们。
http://www.w3schools.com/jsref/jsref_concat_array.asp
Then merge them using concat
method.
http://www.w3schools.com/jsref/jsref_concat_array.asp
var mergedArray = arr1.concat(arr2, arr3);
然后在Javascript数组中使用 sort
方法排序。
ref: http://www.w3schools.com/jsref/jsref_sort.asp
ref: https://developer.mozilla.org / en / JavaScript / Reference / Global_Objects / Array / sort
Then sort using sort
method in Javascript Array.
ref : http://www.w3schools.com/jsref/jsref_sort.asp
ref: 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;
});
使用返回价格B - priceA;
进行降序订购。
jsfiddle: http://jsfiddle.net/diode/FzzHz/
Use return priceB - priceA;
for descending order.
jsfiddle : http://jsfiddle.net/diode/FzzHz/
。
这篇关于添加两个json对象并进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!