我有这个javascript对象:
{{1}}
如何将newArr合并或添加到相关的CountryArray。
预期结果:
{{1}}
答案 0 :(得分:5)
concat?
countryArray = countryArray.concat(newArr);
修改强> 好的,我知道,你想根据newArr中的内容更新countryArray的状态,不再是concat:
<强> EDIT2 强> concat,因为你想根据newArr中的内容添加countryArray的状态
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"]);
答案 1 :(得分:5)
基本上你需要一个JavaScript merging objects by id的变体来合并数组值。
In [814]: x-np.arange(3)[:,None]
Out[814]:
array([[1, 1],
[1, 0],
[0, 1]])
答案 2 :(得分: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++;
});
}
希望有所帮助