Javascript / Angular JS Search Array对象进入Array对象

时间:2017-04-21 23:03:56

标签: javascript angularjs

我的问题是:

我有2个这样的Array对象

var array1 = [{ "id": 1, "name": "potatoe", photo="photo"}, {"id": 2, "name": "budget"}]

var array2 =  [{ "id": 1, "name": "potatoeModified"},{ "id": 3, "name": 
 "UhOhAnotherName"}, {"id": 2, "name": "budget"}]

我想搜索array1 ID对象是否在数组2中,如果是id 1 = 1将被替换名称,如果不存在像id 3那样将被添加。

结果将是

[{ "id": 1, "name": "potatoeModified", photo="photo"}, {"id": 2, "name": "budget"},
{ "id": 3, "name": "UhOhAnotherName"}]

我尝试这样做,但有时我得到一个具有圈复杂度的功能太高而且我不想要一个Super Big功能。我认为解决方案很简单,但我很盲目...... 谢谢:))

2 个答案:

答案 0 :(得分:1)

我会从每个使用id作为键的数组中创建一个临时对象,并将每个项目存储为值。

然后你可以循环遍历数组2的临时对象,并根据临时对象中是否存在id键来调整名称或推送到数组1



var array1 = [{ "id": 1, "name": "potatoe", photo:"photo"}, {"id": 2, "name": "budget"}];
var array2 =  [{ "id": 1, "name": "potatoeModified"},{ "id": 3, "name": 
 "UhOhAnotherName"}, {"id": 2, "name": "budget"}];
 
// create temporary objects using helper function below
var tmp_1 = toObj(array1), 
    tmp_2 = toObj(array2);


// go through array 2 temp object and either adjust name or push to array 1
Object.keys(tmp_2).forEach((key)=>{       
   if(tmp_1[key]){
     // if same id exist from array one, set name
     tmp_1[key].name = tmp_2[key].name;
   }else{
     // push to array one when same id doesn't exist
     array1.push(tmp_2[key]);
   }
});

console.log(array1);
 
// helper function to prevent code duplication
function toObj(arr){
   return arr.reduce((a,c)=>{
     a[c.id] = c;
     return a;
   },{})
}




还有其他一些方法可以使用像Array.prototype.find()这样的东西或嵌套循环来缩短代码,但从长远来看效率会比创建hashmap对象效率低一些

答案 1 :(得分:1)

尝试以下方法:



var array1 = [{ "id": 1, "name": "potatoe", "photo":"photo"}, {"id": 2, "name": "budget"}];

var array2 =  [{ "id": 1, "name": "potatoeModified"},{ "id": 3, "name": 
 "UhOhAnotherName"}, {"id": 2, "name": "budget"}];

array1.map(function(val,i){
  array2.forEach(function(v){
    if(val.id == v.id){
      val.name = v.name;
    }
    else{
      var found = array1.some(function (el) {
        return el.id === v.id;
      });
      if (!found) { array1.push(v); }
    }
  })
  
  return val;   
});

console.log(array1);