JSON 合并、数组推送和排序和删除双精度

json merge, array push & sort & remove doubles

本文关键字:排序 删除 双精度 合并 数组 JSON      更新时间:2023-09-26
var d=[
  {
    'fn':'john',
    'en':'doe',
    'k':['0','5','44']
  },
  {
    'en':'bark',
    'k':[,'25','44']
  }
];


合并(d[0],d[1]);应该返回这个:

  {
    'fn':'john',
    'en':'bark',
    'k':['0','5','25','44']
  }

这是一个常见的合并,唯一的区别是数组如果不同就会被推送(就像 fn 变量一样,它只是被添加,或者像 en 变量一样,它被替换,或者像 k 数组一样,如果它不同,它会被推送)(并同时排序

编辑 1
为我编写脚本不是我所要求的,我不熟悉"is array"和"hasPropery",因为我不熟悉,我正在寻求方向的帮助,并且我正在使用nodejs,所以jquery是一个禁忌。

编辑 2
这是我用来解决问题的代码,以防有人好奇:

function is(obj, type) {
    return Object.prototype.toString.call(obj).slice(8, -1) == type;
}
Array.prototype.unique = function() {
var a=this;
    for(var i=0; i<a.length; ++i) {
        for(var j=i+1; j<a.length; ++j) {
            if(a[i] === a[j])
                a.splice(j--, 1);
        }
    }
    return a;
};
Object.prototype.merge = function(b) {
  var a=this;
  for(var prop in b){
    if(is(b[prop],'Array')&&is(a[prop],'Array')){
      a[prop]=a[prop].concat(b[prop]).unique().sort(function(a,b){return parseInt(a)-parseInt(b)});
    }else{
      a[prop]=b[prop];
    }
  }
  return a;
}
d[

0].merge(d[1]) 准确地给了我所要求的。

要优化数组合并,您可以先对其进行排序,然后再检查唯一。如果您的对象仅包含基元值或数组,而数组仅包含同一时间的基元,则以下内容将起作用:

var tools = {
  merge:function(a,b){
    var ret = {},key,i=-1,len=arguments.length;
    //as in your example, if both items have a property
    // named "en" then the property of the second one is used
    while(i++<len){
      this._merge(ret,arguments[i]);
    }
    for(key in ret){
      if(this._couldBeArray(ret[key])){
         //sort and plice are mutator functions that means 
         //they will change the object when called.
         this._unique(ret[key].sort(this._sortNum));
      }
    };
    return ret;
  },
  _couldBeArray:function(obj){
    return(typeof obj==="object" &&
      /Array']$/.test(Object.prototype.toString.call(obj)));
  },
  _merge:function(a,b){
    var key;
    for(key in b){
      if(b.hasOwnProperty(key)){
        if(this._couldBeArray(b[key])){
            //assuming it's an array, concat only does a 
            //  shallow copy as well though
            a[key]=(a[key])?b[key].concat(a[key]):
              (new b[key].constructor()).concat(b[key]);
        }else{
         a[key]=b[key];
        }
      }
    }
  },
  _unique:function(arr){
    var i=arr.length;
    while(i!==0){
      //unique assumes your array contains only primitives
      //  of same type for example: 0 does not equal "0"
      if(arr[i]===arr[i-1]){
        arr.splice(i,1);
      }
      i--;
    }
    if(arr[i]===arr[i+1])
      arr.splice(i,1);
  },
  _sortNum:function(a,b){
    return parseInt(a,10)-parseInt(b,10);
  }
};
var d=[
  {
    'fn':'john',
    'en':'doe',
    'k':['0','5','44']
  },
  {
    'en':'bark',
    'k':['25','44']
  },
  {
    'another':'another',
    'k':['100','44','45'],
    'primitiveArray':[1,2,3]
  },
  {
    'city':'NY',
    'primitiveArray':[2,3,4,5]
  }
];
console.log(tools.merge.apply(tools,d));

使用 jQuery 的.extend

//$.extend(deepCopy,target,object1,object2);
var data = $.extend(true,{},d[0],d[1]);
console.log(data.en);

您可以像这样单独合并内部数组:

data.k=d[0].k.concat(d[1].k).unique();
console.log(data.k.join(","));

其中unique()是添加到 Array 原型的自定义函数:

Array.prototype.unique = function() {
    var a = this.concat();
    for(var i=0; i<a.length; ++i) {
        for(var j=i+1; j<a.length; ++j) {
            if(a[i] === a[j])
                a.splice(j--, 1);
        }
    }
    return a;
};