将新的数组对象合并到现有对象中js

5
我有这个 JavaScript 对象:
var countryArray = [{
 "country" : 'Indonesia',
 "state" : ['DKI','Bali'],
},
 {
 "country" : 'Malaysia',
 "state" : ['Penang','Johor'],
}];

var newArr = [{ "country" : 'Malaysia', "state" : ['Kelantan'] }]

如何将newArr合并或添加到相关的CountryArray中。
预期结果:
var countryArray = [{
 "country" : 'Indonesia',
 "state" : ['DKI','Bali'],
},
 {
 "country" : 'Malaysia',
 "state" : ['Penang','Johor','Kelantan'],
}];

2
这似乎过于苛刻且不具建设性。这并不是一个简单的问题 - 我在搜索了一段时间后也找不到简单的答案 - 假设没有尝试是不公平的。显然,她是新手,并且是初学者 - 与其潜在地使她疏远,也许您可以解释一下她将来应该怎么做,比如分享她已经尝试过什么? - A. Damond
感谢您的评论,但请不要认为我什么都没试过。我尝试了很多方法,包括concat、push等等。我搜索了所有可能有用的帖子,但是问题仍未解决。这就是我在这个论坛上提问的原因。而且,拥有我在问题中提到的那个脚本,并不意味着我要做很多事情吧?顺便说一句,你们都很好。 - Yusnee
3个回答

5

连接操作符?

countryArray = countryArray.concat(newArr);

编辑 好的,我明白了,你想根据newArr中的内容更新countryArray的状态,不再使用concat方法:

编辑2 如果你想要根据newArr中的内容添加countryArray的州,请使用concat方法。

   var countryArray = [{
     "country" : "Indonesia",
     "state" : ["DKI","Bali"],
    },
     {
     "country" : "Malaysia",
     "state" : ["Penang","Johor"],
    }];

    var newArr = [{ "country" : "Malaysia", "state" : ["Kelantan"] }];

    alert("Before while: " + countryArray[1]["state"]);
    var i=0;
    while(countryArray[i]) {
      var j=0;
      while(newArr[j]) {
        if(countryArray[i]["country"] == newArr[j]["country"]) {
          countryArray[i]["state"] = countryArray[i]["state"].concat(newArr[j]["state"]);
        }
        j++;
      }
      i++;
    }
    alert("After while: " + countryArray[1]["state"]);

请将concat作为您的建议,而不是合并它,而是创建一个新数组 :( - Yusnee
好的,@Yusnee,请看我的编辑 :) - London Smith
@ London Smith。感谢您的帮助。但是使用console.table(countryArray),我丢失了槟城和柔佛。这意味着它只是替换,而不是合并它们。 - Yusnee
我认为这是目的。所以在 while 循环中连接...请查看我的更新 EDIT2 countryArray[i]["state"] = countryArray[i]["state"].concat(newArr[j]["state"]); - London Smith
@Yusnee 哈哈 :) 我很高兴能帮忙。 - London Smith

4

基本上,您想要一个变体JavaScript通过ID合并对象,它合并数组值。

  1. 创建哈希表。
  2. 迭代两个数组并将数据存储在哈希表中,由ID索引。如果已经有具有该ID的某些数据,请合并它。
  3. 获取哈希映射的值数组。

var countryArray = [{
  "country" : 'Indonesia',
  "state" : ['DKI','Bali'],
}, {
  "country" : 'Malaysia',
  "state" : ['Penang','Johor'],
}];
var newArr = [{
  "country" : 'Malaysia',
  "state" : ['Kelantan']
}];
function mergeById(objs, id) {
  var hash = new Map();
  objs.forEach(function(obj) {
    var merged = hash.get(obj[id]) || {};
    Object.keys(obj).forEach(function(key) {
      if (key === id) return merged[id] = obj[id];
      if (!merged[key]) merged[key] = [];
      if (Array.isArray(obj[key])) [].push.apply(merged[key], obj[key]);
      else merged[key].push(obj[key]);
    })
    hash.set(obj[id], merged)
  });
  return Array.from(hash.values());
}
console.log(mergeById(countryArray.concat(newArr), "country"));


@Oriol 上帝保佑你。感谢所有为我浪费时间的人。现在是早上8:25,我在我的国家。整晚我都没有睡觉,一直在寻求帮助。 - Yusnee

1

如果您想要合并,有时还需要进行拼接。尝试这样做:

var countryArray = [{
     "country" : "Indonesia",
     "state" : ["DKI","Bali"],
    },
     {
     "country" : "Malaysia",
     "state" : ["Penang","Johor"],
    }];

合并新进数据;

 var newArr = [{ "country" : "Malaysia", "state" : ["Kelantan"] }];   

 MergeArray(countryArray,newArr);
 console.table(countryArray);

从传入的数据中拼接表单;
var DelArray = [{ "country" : "Malaysia", "state" : ["Penang"] }];

SpliceArray(countryArray,DelArray);
console.table(countryArray);

和相关功能;
function MergeArray(countryArray,newArr) {  
 var a = 0;
  $.each(newArr, function (key, data1) {
     var b = 0;
     $.each(countryArray, function (key, data2) { 

        if(data1.country == data2.country) { // match the same country

    countryArray[b]["state"] =  countryArray[b]["state"].concat(newArr[a]["state"]);

        }

    b++; });
  a++; });  
}

function SpliceArray(countryArray,DelArray) { 
    var a=0;
            $.each(DelArray, function (key, data1) { 
              var b=0;
              $.each(countryArray, function (key, data2) { 

                      if(data1.country == data2.country) {  // get same country    

                         console.log(countryArray[b]["state"]) //   ["Penang", "Johor", "Kelantan"]

                          for(var c=0; c < countryArray[b]["state"].length; c++){   // loop in countryArray state[]

                           console.log(DelArray[a]['state']); // to remove :  ["Penang"]

                              if(countryArray[b]["state"][c] == DelArray[a]['state'] ) {

                                 countryArray[b]["state"].splice(c,1); // remove ["Penang"]

                              }
                          }
                      }
              b++; 
              });
        a++;
        });

  } 

希望能有所帮助。

非常感谢您的努力。但是我已经有了我的解决方案。基本上是一样的。 - Yusnee

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接