ForgeTotal.js 5
en

Total.js 5

Compare two lists with DIFFARR: what to add, update and remove

Total.js 5 · total5@0.0.19 utilitiesarraysforms Executed against Total.js 5

DIFFARR(property, saved, submitted) compares two arrays of objects by one property and returns an object with three lists:

  • add: the objects of submitted whose property is not in saved
  • upd: for the objects that are in both, { db, form } with the saved object and the submitted one
  • rem: the values of the property (not the objects) of the items of saved that are not in submitted

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.

controllers/lists.js
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
	});
}