數組a
[{key:1,name:'name1'},{key:2,name:'name2'},{key:3,name:'name3'},{key:4,name:'name4'},{key:5,name:'name5'}]
陣列b是在陣列a的一部份
[{key:1,name:'name1'},{key:2,name:'name2'}]
數組c是在數組b的基礎上進行修改
[{key:1,name:'name11'},{key:22,name:'name22'}]
現在需要最後的結果為key:1被修改,key:2被刪除,key:3,key:4,key:5無變化保留,key:22被加
[{key:1,name:'name11'},{key:3,name:'name3'},{key:4,name:'name4'},{key:5,name:'name5'},{key:22,name:'name22'}]
請問一下如何才能實現這個邏輯
学习ing2017-06-26 10:54:07
var a = [{key:1,name:'name1'},{key:2,name:'name2'},{key:3,name:'name3'},{key:4,name:'name4'},{key:5,name:'name5'}];
var b = [{key:1,name:'name1'},{key:2,name:'name2'}];
var c = [{key:1,name:'name11'},{key:22,name:'name22'}];
var d = [];
d = $.extend(a,(b,c));
console.log(d);
extend方法 跟git 的merge差不多
我這樣寫應該會得到你最後想要的那種結果
typecho2017-06-26 10:54:07
如果找不到好的工具,或不想污染命名空間,那就把陣列解耦,這樣應該可以滿足你的要求
let a = [{ key: 1, name: 'name1' }, { key: 3, name: 'name3' }, { key: 2, name: 'name2' }, { key: 4, name: 'name4' }, { key: 5, name: 'name5' }];
let b = [{ key: 1, name: 'name1' }, { key: 2, name: 'name2' }];
let c = [{ key: 22, name: 'name22' }, { key: 1, name: 'name11' }];
let akeys = a.map(x => x.key);
let aname = a.map(x => x.name)
let bkeys = b.map(x => x.key)//1,2
let bname = b.map(x => x.name)
let ckeys = c.map(x => x.key)//1,22
let cname = c.map(x => x.name)
ckeys.forEach(function (key, index) {
if (bkeys.includes(key))
a[akeys.indexOf(key)].name = cname[ckeys.indexOf(key)]
else {
a[akeys.indexOf(bkeys[1])].key = key
a[akeys.indexOf(bkeys[1])].name = cname[ckeys.indexOf(key)]
}
})
console.log(a)
漂亮男人2017-06-26 10:54:07
給你一段程式碼拿去想像(只適用與數組合併),將下面的程式碼拿到控制台輸出一下就行了
function arrayExtends(){
var arrs = Array.prototype.slice.call(arguments);
if(arrs.length < 2){
return arrs[0];
}
var save = arrs.pop(),
now;
while(now = arrs.pop()){
for( var i = 0 , len = save.length; i < len; i++ ){
now[i] = save[i];
}
save = now;
}
return save;
}
arrayExtends([1,2,3,6,7],[4,5,{hello:"world"}],[{key:1,name:"zz"}]);
然後修改下適應你的需求:
function arrayExtends(){
var arrs = Array.prototype.slice.call(arguments);
if(arrs.length < 2){
return arrs[0];
}
var save = arrs.pop(),
now;
while(now = arrs.pop()){
for( var i = 0 , len = save.length; i < len; i++ ){
now[i] = save[i];
}
save = now;
}
var result = save.sort(function(a,b){
return a.key - b.key;
});
return result;
}
arrayExtends([{key:1,name:"zz"}],[{key:2,name:"zz"},{key:3,name:"zz"}]);