-
Notifications
You must be signed in to change notification settings - Fork 0
/
add-props.js
60 lines (50 loc) · 1.45 KB
/
add-props.js
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
/*!
* Add Props, http://tpkn.me/
*/
function addProps(obj, props, values){
var check = function(p, level, list, val){
if(!Object.prototype.hasOwnProperty.call(level, p)){
level[p] = {};
}
if(typeof val !== 'undefined' && val != null && list.length == 0){
level[p] = val;
}
}
var loop = function(level, list, val){
if(list.length){
var p = list.shift();
// Check if it's regular_property_Name (accessible through dot). Skip further steps if it's not
if(!/(\W|^[\d\s]+$)/i.test(p)){
check(p, level, list, val);
}else{
return;
}
loop(level[p], list, val);
}
}
if(Object.prototype.toString.call(obj) != '[object Object]'){
values = props;
props = obj;
obj = {};
}
if(!Array.isArray(props) && typeof props !== 'string'){
return {};
}
if(Array.isArray(props)){
for(var i = 0, len = props.length; i < len; i++){
loop(obj, String(props[i]).split('.'), Array.isArray(values) ? values[i] : values);
}
}else{
loop(obj, String(props).split('.'), values);
}
return obj;
}
if(typeof module !== 'undefined' && typeof module.exports !== 'undefined'){
module.exports = addProps;
}else{
if(typeof define === 'function' && define.amd){
define([], function(){
return addProps;
});
}
}