Completed
Push — master ( d0d7d8...965e58 )
by greg
04:24 queued 01:45
created

jsonObject.js ➔ setObjByString   C

Complexity

Conditions 8
Paths 11

Size

Total Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
cc 8
c 2
b 1
f 0
nc 11
nop 3
dl 0
loc 25
rs 5.3846
1
export function setObjByString(obj, str, val) {
2
  var keys, key
3
  //make sure str is a string with length
4
  if (!str || !str.length || Object.prototype.toString.call(str) !== '[object String]') {
5
    return false
6
  }
7
  if (obj !== Object(obj)) {
8
      //if it's not an object, make it one 
9
    obj = {}
10
  }
11
  keys = str.split('.')
12
  while (keys.length > 1) {
13
    key = keys.shift()
14
    if (obj !== Object(obj)) {
15
          //if it's not an object, make it one 
16
      obj = {}
17
    }
18
    if (!(key in obj)) {
19
          //if obj doesn't contain the key, add it and set it to an empty object 
20
      obj[key] = {}
21
    }
22
    obj = obj[key]
23
  }
24
  return obj[keys[0]] = val
25
}