@rjlevy/

JS: validate changes between two objects

HTML, CSS, JS

No description

fork
loading
Files
  • index.html
  • reference.txt
  • script.js
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<!DOCTYPE html>
<html>

<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width">
	<title>repl.it</title>
	<script src="https://cdn.jsdelivr.net/npm/lodash">

	</script>
</head>

<body>
	<script>
		const snapshotObject = {
        "taskTypeId": 2,
        "taskStatusId": 40,
        "scheduleDate": null,
        "timeStarted": null,
        "timeCompleted": null,
        "taskOptionsId": [3, 4, 1],
        "taskAdditions": [
          20,
          27,
          28
        ]
      };

      const updatedObject = {
        "taskTypeId": 7,
        "taskStatusId": 1,
        "scheduleDate": null,
        "timeCompleted": null,
        "timeStarted": null,
        "taskOptionsId": [1, 3, 4],
        "taskAdditions": [
          23,
          27,
          28
        ],
      };

      function isArray (value) {
        return value && typeof value === 'object' && value.constructor === Array;
      }
      
      const whitelist = ['scheduleDate', 'timeStarted', 'timeCompleted'];
      
      function checkForChanges(snapshot, updated) {
        return Object.keys(snapshot).reduce((acc, key) => {
          if (isArray(snapshot[key])) {
            if (snapshot[key].length !== updated[key].length) {
              acc[key] = updated[key];
            } else {
              const matching = snapshot[key].filter(item => updated[key].includes(item));
              if (matching.length !== snapshot[key].length) acc[key] = updated[key];
            }
          } else {
            if (snapshot[key] !== updated[key] || whitelist.includes(key)) {
              acc[key] = updated[key];
            }
          }
          return acc;
        }, {});
      }

      console.log(checkForChanges(snapshotObject, updatedObject));

	</script>
</body>

</html>
result
console