简体   繁体   中英

How to merge two json and sort through time values with Javascript

I have 2 json, my job now is to merge the two into a json and sorted by time value in the json and values ​​in json remain as originally. I have tried many ways but can not do, and you can help me? thank you.

json 1

{"data":[{"messageString":"xin chao lqh 1","dateSent":"2013-06-13T02:58:37.0000000-07:00","fromUserID":"4091471","userName":"yanbi"},{"messageString":"xin chao lqh 2","dateSent":"2013-06-13T02:58:54.0000000-07:00","fromUserID":"3569333","userName":"vuquyet"},{"messageString":"xin chao lqh 2","dateSent":"2013-06-13T02:59:05.0000000-07:00","fromUserID":"3878204","userName":"duongdung"}]}

json 2

{"data":[{"messageString":"Hi ban h?i","toUserID":"3600311","dateSent":"2013-05-06T21:04:23.0000000-07:00"},{"messageString":"yes","toUserID":"4091471","dateSent":"2013-06-15T02:16:58.0000000-07:00"},{"messageString":"xin chao duongdung13","toUserID":"3844013","dateSent":"2013-06-10T21:54:56.0000000-07:00"},{"messageString":"xin chao duongdung13 l?n 2 ","toUserID":"3844013","dateSent":"2013-06-10T21:55:06.0000000-07:00"},{"messageString":"xin chao duongdung13 l?n 3","toUserID":"3844013","dateSent":"2013-06-10T21:55:19.0000000-07:00"},{"messageString":"oh chào yanbi","toUserID":"4091471","dateSent":"2013-06-14T23:31:38.0000000-07:00"},{"messageString":"yanbi bi?t tôi ah ?","toUserID":"4091471","dateSent":"2013-06-14T23:32:36.0000000-07:00"},{"messageString":"vâng tôi chào b?n","toUserID":"3569333","dateSent":"2013-06-14T23:42:35.0000000-07:00"},{"messageString":"sao v?yb?n ?","toUserID":"4091471","dateSent":"2013-06-14T23:43:45.0000000-07:00"}]}

if you have jQuery you can use jQuery.extend(json1, json2); more info here

If the JSONs is not already parsed, you must parse them:

json1 = JSON.parse(json1_string);
json2 = JSON.parse(json2_string);

With the JSONs parsed, just concat the arrays and sort them:

array = json1.data.concat(json2.data);
array.sort(function(a, b) {
  if(a.dateSent < b.dateSent) {
    return -1;
  } 
  if(a.dateSent > b.dateSent) {
    return 1;
  } else {
    return 0;
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM