-
Notifications
You must be signed in to change notification settings - Fork 896
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
实现一个 setter 方法 #386
Labels
Comments
|
const setter = function (content, key, value) {
if (!content || typeof content !== "object") return false;
const paths = key.split(".") || [];
// 根据paths, 不停的获取最后对应的数据和key
const { obj, keyName } = paths.reduce((accu, k, index) => {
if (index !== paths.length - 1) return accu[k];
return { obj: accu, keyName: k };
}, content);
obj[keyName] = value;
return obj;
};
let n = {
a: {
b: {
c: { d: 1 },
bx: { y: 1 },
},
ax: { y: 1 },
},
};
// 修改值
setter(n, "a.b.c.d", 3);
console.log(n.a.b.c.d); //3
setter(n, "a.b.bx", 1);
console.log(n.a.b.bx); //1
console.log(n); |
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The text was updated successfully, but these errors were encountered: