gpt4 book ai didi

javascript - json 合并、数组推送、排序和删除 double

转载 作者:行者123 更新时间:2023-12-02 18:08:21 25 4
gpt4 key购买 nike

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));

关于javascript - json 合并、数组推送、排序和删除 double ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19902209/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com