如何将一个数组元素添加到另一个数组。例如,将ganguly添加到arrayA并删除那里的sachin

时间:2018-06-07 09:38:50

标签: javascript json

 var arrayA = [ {"name":"sachin","location":"mum"} ]; 
 var arrayB = [ {"name":"Ganguly","location":"mum"} ]; 
 var newArray = arrayA.push(JSON.stringify((arrayB[0].name)));
 console.log(newArray); console.log(arrayA);`

2 个答案:

答案 0 :(得分:0)

如果您不想创建新数组,那么:

var arrayA = [ {"name":"sachin","location":"mum"} ]; 
var arrayB = [ {"name":"Ganguly","location":"mum"} ]; 
arrayA[0].name = arrayB[0].name;
console.log(arrayA);`

答案 1 :(得分:0)

由于它是一个对象数组并且假设将来有多个元素,你需要过滤掉ganguly对象并将其添加到newArray,并且要删除sachin对象,你可以使用相同的过滤器函数。

var gangulyArr = arrayB.filter(function(el) {
    return el.name === "Ganguly";
});

var newArray  = arrayA.concat(gangulyArr);//gangulyArr has all objs named 
 // ganguly, even if its one

arrayA = arrayA.filter(function(el) {
    return el.name !== "sachin"; // to remove sachin from original array
});

如果你想写更少的代码,更喜欢underscore,它有很好的方法 - 查找,删除,拒绝,采摘等,

 var gangulyObj =  _.find(arrayB, 'name', 'Ganguly');
 var newArray = arrayA;
 if(gangulyObj) {
     newArray.push(gangulyObj);
 }

 arrayA = _.reject(arrayA , function(el) { return el.name === "sachin"; });