user2402616
user2402616

Reputation: 1563

Check if array of objects has changed

I have an array that could contain objects. Objects can either be added to it or have a property modified. I want to check if the array has changed at all (could be element(s) added or simply just have one object have a key changed), and then update the DB based on the potential change.

Just wanna know if what I have will cover all cases and/or if there is a better way to do it.

const origArrayCopy = JSON.stringify(origArray);

someFnThatPotentiallyChanges(origArray);

if (origArrayCopy !== JSON.stringify(origArray)) {
    updateDB(arr);
} else {
    console.log('NO DIFF');
}

And here's a jsFiddle I created to test around with https://jsfiddle.net/j4eqwmp6/

Converting the object to a string using stringify should account for deep-nested changes, right? Any insights on this implementation and is there now a more appropriate way to do it?

Upvotes: 3

Views: 6585

Answers (1)

trincot
trincot

Reputation: 350766

Using JSON.stringify is certainly a possibility.

An alternative, is to wrap the object (array) in a proxy, and do that for every nested object as well. Then trap all actions that mutate those objects.

Here is how that could look:

function monitor(obj, cb) {
    if (Object(obj) !== obj) return obj;
    for (let key of Object.keys(obj)) {
        obj[key] = monitor(obj[key], cb);
    }
    return new Proxy(obj, {
        defineProperty(...args) {
            cb();
            return Reflect.defineProperty(...args);
        },
        deleteProperty(...args) {
            cb();
            return Reflect.deleteProperty(...args);
        },
        set(...args) {
            cb();
            return Reflect.set(...args);
        }
    });
};

// Example array
let origArray = [{x: 1}, { child: { y: 1} }];

// Activate the proxy:
let dirty = false;
origArray = monitor(origArray, () => dirty = true);

// Perform a mutation
origArray[1].child.y++;

console.log(dirty); // true
console.log(origArray);

Upvotes: 1

Related Questions