我有这个javascript对象:
var countryArray = [{
"country" : 'Indonesia',
"state" : ['DKI','Bali'],
},
{
"country" : 'Malaysia',
"state" : ['Penang','Johor'],
}];
var newArr = [{ "country" : 'Malaysia', "state" : ['Kelantan'] }]
Run Code Online (Sandbox Code Playgroud)
如何合并或添加newArr到相关的CountryArray.
预期结果 :
var countryArray = [{
"country" : 'Indonesia',
"state" : ['DKI','Bali'],
},
{
"country" : 'Malaysia',
"state" : ['Penang','Johor','Kelantan'],
}];
Run Code Online (Sandbox Code Playgroud)
concat?
countryArray = countryArray.concat(newArr);
Run Code Online (Sandbox Code Playgroud)
编辑 好的,我知道,你想根据newArr中的内容更新countryArray的状态,不再更多:
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"]);
Run Code Online (Sandbox Code Playgroud)
如果要合并,有时也需要拼接。尝试这个 :
var countryArray = [{
"country" : "Indonesia",
"state" : ["DKI","Bali"],
},
{
"country" : "Malaysia",
"state" : ["Penang","Johor"],
}];
Run Code Online (Sandbox Code Playgroud)
与传入的新数据合并;
var newArr = [{ "country" : "Malaysia", "state" : ["Kelantan"] }];
MergeArray(countryArray,newArr);
console.table(countryArray);
Run Code Online (Sandbox Code Playgroud)
对传入的数据进行拼接;
var DelArray = [{ "country" : "Malaysia", "state" : ["Penang"] }];
SpliceArray(countryArray,DelArray);
console.table(countryArray);
Run Code Online (Sandbox Code Playgroud)
以及相关功能;
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++;
});
}
Run Code Online (Sandbox Code Playgroud)
希望有帮助
| 归档时间: |
|
| 查看次数: |
186 次 |
| 最近记录: |