-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvue-set.js
More file actions
43 lines (33 loc) · 1.09 KB
/
vue-set.js
File metadata and controls
43 lines (33 loc) · 1.09 KB
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
const assign = (object, key, value) => {
object[key] = value
}
export default function (object, path, value, setter) {
// make sure we have a path and a valid object
if (!path) return
if (!object || typeof object !== 'object') return
// make sure the setter is a function
if (typeof setter !== 'function') setter = assign
// make sure the path is an array
if (!Array.isArray(path)) path = [ path ]
// maintain a reference to the relevant attribute
let target = object
// get the last index
let lastIndex = path.length - 1
// iterate through keys in the path
for (let index = 0; index <= lastIndex; index += 1) {
// get the key
let key = path[index]
// set the value at target[key]
if (index === lastIndex) setter(target, key, value)
else {
// overwrite any non-object attributes
if (!target[key] || typeof target[key] !== 'object')
setter(target, key, {})
setter(target, key, Object.assign(target[key], {}))
// reference the next relevant attribute
target = target[key]
}
}
// just in case
return object
}