Object对象深度赋值/取值
支持Object和Array混合型对象深度赋值/取值。
其中,用到的对象类型判断方法,详见《JavaScript中Object对象类型判断》;
// 根据路径创建对象
export const createObject = (path, value) => {
let keyPath = [];
if (isArray(path)) keyPath = [...path];
if (keyPath.length) {
const key = keyPath.shift();
if (isNumber(key)) {
const object = new Array(key + 1);
object[key] = createObject(keyPath, value);
return object;
} else return { [key]: createObject(keyPath, value) };
} else return value;
};
export const setPathValue = (object, path, value) => {
let keyPath = [];
if (isArray(path)) keyPath = [...path];
if (keyPath.length) {
const key = keyPath.shift();
if (object && object[key])
object[key] = setPathValue(object[key], keyPath, value);
else object[key] = createObject(keyPath, value);
} else object = value;
return object;
};
export const getPathValue = (object, path) => {
let keyPath = [];
if (isArray(path)) keyPath = [...path];
else if (isString(path) || isNumber(path)) keyPath = [path];
if (keyPath.length) {
const key = keyPath.shift();
if (object && !isUndefined(object[key]))
return getPathValue(object[key], keyPath);
else return undefined;
} else return object;
};
示例:
const object = createObject(["aaa", "bbb", 3, "ccc"], {ddd: "初始值"});
setPathValue(object, ["aaa", "bbb", 3], {eee: "新赋值"});
const value = getPathValue(object, ["aaa", "bbb", 3, "eee"]);