-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
39 lines (38 loc) · 1.19 KB
/
index.js
File metadata and controls
39 lines (38 loc) · 1.19 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
/*
* Given an object, an array of properties and a value,
* recursively create single property objects if needed, and assign the value
* to the last property created.
*
* EG:
* var myObj = {}
* myObj.assignPath(['a','b','c'],'hello');
* > { a : { b: {c: 'hello' } } }
* myObj.assignPath(['a','b','d'],'goodbye');
* > { a : { b: {c: 'hello', d: 'goodbye' } } }
*/
if (!Object.prototype.assignPath) {
Object.prototype.assignPath = function(keyPath, value, append) {
append = append || false;
_assignPath(this,keyPath,value, append);
}
var _assignPath = function(obj,keyPath,value,append) {
lastKeyIndex = keyPath.length-1;
for (var i = 0; i < lastKeyIndex; ++ i) {
key = keyPath[i];
if (!(key in obj))
obj[key] = {}
obj = obj[key];
}
if (append) {
if (Object.prototype.toString.call(obj[keyPath[lastKeyIndex]]) === '[object Array]') {
obj[keyPath[lastKeyIndex]].push(value);
}
else {
obj[keyPath[lastKeyIndex]] = [value];
}
}
else {
obj[keyPath[lastKeyIndex]] = value;
}
}
}