Compare two lists with DIFFARR: what to add, update and remove
DIFFARR(property, saved, submitted) compares two arrays of objects by one property and returns an object with three lists:
add: the objects ofsubmittedwhose property is not insavedupd: for the objects that are in both,{ db, form }with the saved object and the submitted onerem: the values of the property (not the objects) of the items ofsavedthat are not insubmitted
It is the usual step of saving an editable list: the form sends the whole list and you need to know what was created, what changed and what was deleted. The values are compared with ==, so 1 and '1' are the same item.
const saved = [
{ id: 1, name: 'Book' },
{ id: 2, name: 'Pen' },
{ id: 3, name: 'Lamp' }
];
exports.install = function() {
ROUTE('POST /sync/', sync);
};
function sync($) {
const diff = DIFFARR('id', saved, $.body.items);
$.json({
add: diff.add,
update: diff.upd.map(n => ({ id: n.db.id, from: n.db.name, to: n.form.name })),
remove: diff.rem
});
}