Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 1x 1x 1x 14x 13x 12x 11x 11x 11x 11x 10x 5x 4x 5x 4x 5x 4x 3x 1x | var $type = require('./type');
var $get = require('./get');
var $keyPathSplit = require('../str/keyPathSplit');
/**
* 向对象路径设置值(简易版)
* @method obj/set
* @see [lodash.set](https://lodash.com/docs/4.17.15#set)
* @param {Object|Array} obj 要设置值的对象或者数组
* @param {String} xpath 要取值的路径
* @param {Any} value 要设置的值
* @returns {undefined}
* @example
* var $set = require('@spore-ui/kit/packages/obj/set');
* var obj = {a: {b: {c: 1}}};
* $set(obj, 'a.b.c', 2);
* console.info(obj.a.b.c) // 2
*/
function set(obj, xpath, value) {
if (!obj) return;
if (typeof xpath !== 'string') return;
if (!xpath) return;
var arrXpath = $keyPathSplit(xpath);
var key = arrXpath.pop();
var target = $get(obj, arrXpath.join('.'));
if (!target) return;
if ($type(target) === 'array') {
if (/^\d+$/.test(key)) {
key = parseInt(key, 10);
}
if ($type(value) !== 'undefined') {
target[key] = value;
}
} else if ($type(target) === 'object') {
if ($type(value) !== 'undefined') {
target[key] = value;
}
}
}
module.exports = set;
|