Published on

Watching for Object and Array Changes in JavaScript

Authors

Sometimes you might want to watch changes to your object or array and do some operations depending on what's changed.

For such cases, on-change by Sindre Sorhus might be a good choice for us.

This package uses Proxy API under the hood to watch for the changes. I even watch deep properties like object.a.foo = true or even with an array like object.a.b[0].c = true

Dependency

npm install on-change

Snippet

// Based on on-change's README example
import onChange from 'on-change';

const object = {
	a: {
		foo: false,
		b: [
			{
				c: false
			}
		]
	}
};

const watchedObject = onChange(object, function (path, value, previousValue) {
	console.log('path:', path);
	console.log('value:', value);
	console.log('previousValue:', previousValue);
});

watchedObject.a.foo = true

/*
path: a.foo
value: true
previousValue: false
*/

Check out their docs for more snippets and details about its configuration.

Happy watching Objects!