I am having a selected object that has the following structure
const selected = [
{ field: { prop1: "value1" }, isDeleted: true, isSelected: false },
{ field: { prop1: "value2" }, isDeleted: true, isSelected: false },
{ field: { prop1: "value3" }, isDeleted: false, isSelected: false }
];
Also I am having current objects with the following structure
const current = [
{ field: { prop1: "value2" }, isDeleted: false, isSelected: false },
{ field: { prop1: "value1" }, isDeleted: false, isSelected: false }
];
Now basically I have return appended list with remaining objects that has isDeleted: true
in current, and then take the objects of selected
that has isDeleted: true
and append to the current, with isDeleted: false
i sequence of its presence in selected
For the above input the output will be,
const output = [
{ field: { prop1: "value3" }, isDeleted: false, isSelected: false },
{ field: { prop1: "value2" }, isDeleted: false, isSelected: false },
{ field: { prop1: "value1" }, isDeleted: false, isSelected: false }
];
As the object in current with field prop1
has isDeleted :false
, so that becomes the first object. And remaining objects of current
are matched with selected
to find a match using name and isDeleted: true
and adding it to the output, with its isDeleted
changing to false
.
Code that I tried
const selected = [
{ field1: { prop1: "value1" }, isDeleted: true, isSelected: false },
{ field1: { prop1: "value2" }, isDeleted: true, isSelected: false },
{ field1: { prop1: "value3" }, isDeleted: false, isSelected: false }
];
const current = [
{ field1: { prop1: "value1" }, isDeleted: false, isSelected: false },
{ field1: { prop1: "value2" }, isDeleted: false, isSelected: false }
];
const selectedModified = selected.map((sel) => {
const found = current.find(
(cur) => cur.field.prop1 === sel.field.prop1 && sel.isDeleted
);
if (found) {
return {
field: sel.field,
isDeleted: false,
isSelected: false
};
}
return sel;
});
const filtered = [...(selectedModified || []), ...current].filter(
filterBy("prop1")
);
const filterBy = (key, set = new Set()) => (o) =>
!set.has(o.file[key]) && set.add(o.file[key]);
console.log(filtered);
CodePudding user response:
Wouldn't that just be: concatenating the two arrays and filtering the result for isDeleted === false
?
const selected = [
{ field: { prop1: "value1" }, isDeleted: true, isSelected: false },
{ field: { prop1: "value2" }, isDeleted: true, isSelected: false },
{ field: { prop1: "value3" }, isDeleted: false, isSelected: false }
];
const current = [
{ field: { prop1: "value2" }, isDeleted: false, isSelected: false },
{ field: { prop1: "value1" }, isDeleted: false, isSelected: false }
];
const output = selected.concat(current).filter(v => !v.isDeleted);
document.querySelector(`pre`).textContent = JSON.stringify(output, null, 2);
<pre></pre>