UNPKG

2.19 kBJavaScriptView Raw
1var staticParseInt = require('./staticParseInt')
2
3var helperGetHGSKeys = require('./helperGetHGSKeys')
4
5var hasOwnProp = require('./hasOwnProp')
6
7var sKeyRE = /(.+)?\[(\d+)\]$/
8
9function setDeepProps (obj, key, isEnd, nextKey, value) {
10 if (obj[key]) {
11 if (isEnd) {
12 obj[key] = value
13 }
14 } else {
15 var index
16 var rest
17 var currMatchs = key ? key.match(sKeyRE) : null
18 if (isEnd) {
19 rest = value
20 } else {
21 var nextMatchs = nextKey ? nextKey.match(sKeyRE) : null
22 rest = nextMatchs && !nextMatchs[1] ? new Array(staticParseInt(nextMatchs[2]) + 1) : {}
23 }
24 if (currMatchs) {
25 if (currMatchs[1]) {
26 // 如果为对象中数组
27 index = staticParseInt(currMatchs[2])
28 if (obj[currMatchs[1]]) {
29 obj[currMatchs[1]][index] = rest
30 } else {
31 obj[currMatchs[1]] = new Array(index + 1)
32 obj[currMatchs[1]][index] = rest
33 }
34 } else {
35 // 如果为数组
36 obj[currMatchs[2]] = rest
37 }
38 } else {
39 // 如果为对象
40 obj[key] = rest
41 }
42 return rest
43 }
44 return obj[key]
45}
46
47/**
48 * 设置对象属性上的值。如果属性不存在则创建它
49 * @param {Object/Array} obj 对象
50 * @param {String/Function} property 键、路径
51 * @param {Object} value 值
52 */
53function set (obj, property, value) {
54 if (obj) {
55 if ((obj[property] || hasOwnProp(obj, property)) && !isPrototypePolluted(property)) {
56 obj[property] = value
57 } else {
58 var rest = obj
59 var props = helperGetHGSKeys(property)
60 var len = props.length
61 for (var index = 0; index < len; index++) {
62 if (isPrototypePolluted(props[index])) {
63 continue
64 }
65 var isEnd = index === len - 1
66 rest = setDeepProps(rest, props[index], isEnd, isEnd ? null : props[index + 1], value)
67 }
68 }
69 }
70 return obj
71}
72
73/**
74 * Blacklist certain keys to prevent Prototype Pollution
75 * @param {string} key
76 */
77function isPrototypePolluted(key) {
78 return key === '__proto__' || key === 'constructor' || key === 'prototype'
79}
80
81module.exports = set