How to deep watch an array of objects and calculating the change with Vue.js?

Sometimes, we want to deep watch an array of objects and calculating the change with Vue.js.

In this article, we’ll look at how to deep watch an array of objects and calculating the change with Vue.js.

How to deep watch an array of objects and calculating the change with Vue.js?

To deep watch an array of objects and calculating the change with Vue.js, we can add a deep watcher and get the old and new values from the watcher method.

For instance, we write

<template>
  <div id="app">
    <input
      type="text"
      v-for="(person, index) in people"
      v-model="people[index].age"
    />
  </div>
</template>

<script>
new Vue({
  el: "#app",
  data: {
    people: [
      { id: 0, name: "jane", age: 27 },
      { id: 1, name: "joe", age: 32 },
      { id: 2, name: "bob", age: 38 },
    ],
  },
  watch: {
    people: {
      handler(val, oldVal) {
        const changed = val.filter((p, idx) => {
          return Object.keys(p).some((prop) => {
            return p[prop] !== oldVal[idx][prop];
          });
        });
        console.log(changed);
      },
      deep: true,
    },
  },
});
</script>

to add the watcher for the people array.

And then we get the new and old value of people with val and oldVal respectively.

Next, we compute the change between val and oldVal with

const changed = val.filter((p, idx) => {
  return Object.keys(p).some((prop) => {
    return p[prop] !== oldVal[idx][prop];
  });
});

to call val.filter with a callback to check if a property in the object is different from the old value.

We set deep to true to make Vue watch all the contents of people for changes.

Conclusion

To deep watch an array of objects and calculating the change with Vue.js, we can add a deep watcher and get the old and new values from the watcher method.