跳到主要内容

set

2024年04月08日
柏拉文
越努力,越幸运

一、认识


二、实现


2.1 Bolawen reduce

实现

function set(obj, path, value) {
const pathRegExp = /[,\[\].]+?/;
const keys = Array.isArray(path)
? path
: path.split(pathRegExp).filter(Boolean);

keys.reduce((acc, key, index) => {
if (index === keys.length - 1) {
acc[key] = value;
} else {
if (!acc[key]) {
acc[key] = {};
}
return acc[key];
}
}, obj);
}

测试

const object = { a: [{ b: { c: 3 } }] };

set(object, "a[0].b.c", 4);
console.log(object.a[0].b.c);
// => 4

set(object, ["x", "0", "y", "z"], 5);
console.log(object.x[0].y.z);
// => 5

2.2 Bolawen for…of

实现

function set(obj, path, value) {
const pathRegExp = /[,\[\].]+?/;
const keys = Array.isArray(path)
? path
: path.split(pathRegExp).filter(Boolean);

for (const key of keys.slice(0, -1)) {
if (!obj[key]) {
obj[key] = {};
}
obj = obj[key];
}

obj[keys[keys.length - 1]] = value;
}

测试

const object = { a: [{ b: { c: 3 } }] };

set(object, "a[0].b.c", 4);
console.log(object.a[0].b.c);
// => 4

set(object, ["x", "0", "y", "z"], 5);
console.log(object.x[0].y.z);
// => 5