我想读取array2并从array1中删除项目并将新项目添加到array1:
如果参数“已删除”为1,那么我想删除此项目。 如果参数“已删除”为0,那么我想添加项目。
如何使用javascript制作以下解决方案?
我有两个数组:
var array1 = [
{ItemId: "1", Name: "John"},
{ItemId: "2", Name: "George"},
{ItemId: "3", Name: "Peter"}
]
和
var array2 = [
{ItemId: "1", Name: "John", Removed: "1"},
{ItemId: "4", Name: "Mario", Removed: "0"},
{ItemId: "5", Name: "Mike", Removed: "0"}
]
我想要以下结果:
var array1 = [
{ItemId: "2", Name: "George"},
{ItemId: "3", Name: "Peter"},
{ItemId: "4", Name: "Mario"},
{ItemId: "5", Name: "Mike"}
]
答案 0 :(得分:2)
试试这个:
注意:这不会检查具有相同“名称”或相同“ItemId”的重复条目。你可能也想这样做。
var array1 = [
{ItemId: "1", Name: "John"},
{ItemId: "2", Name: "George"},
{ItemId: "3", Name: "Peter"}
];
var array2 = [
{ItemId: "1", Name: "John", Removed: "1"},
{ItemId: "4", Name: "Mario", Removed: "0"},
{ItemId: "5", Name: "Mike", Removed: "0"}
];
for(var i = 0; i < array2.length; i++) {
if(array2[i]["Removed"] == "1") {
// Remove elements
for(var j = 0; j < array1.length; j++) {
if(array1[j]["Name"] == array2[i]["Name"]) {
array1.splice(j,1);
}
}
} else {
item = {};
item["ItemId"] = array2[i]["ItemId"];
item["Name"] = array2[i]["Name"];
array1.push(item);
}
}
答案 1 :(得分:-1)
使用https://stackoverflow.com/a/1144249/1922787中的Object.equals()
:
function mergeArrays(array, operations) {
var obj;
var removed;
for (var i = 0; i < operations.length; i++) {
obj = operations[i];
removed = obj.Removed;
delete obj.Removed;
if (removed === '0') { array.push(obj); }
if (removed === '1') { array = removeObjFromArray(array, obj); }
}
return array;
}
function removeObjFromArray(array, obj) {
for (var i = 0; i < array.length; i++) {
if (obj.equals(array[i])) {
array.splice(i, 1);
break; // assuming you don't have dupplicated objects in your array
}
}
return array;
}
array1 = mergeArrays(array1, array2);