Skip to content

Instantly share code, notes, and snippets.

@JerryC8080
Last active January 1, 2021 06:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JerryC8080/56e4b0457de3b54dedfee59667062f4b to your computer and use it in GitHub Desktop.
Save JerryC8080/56e4b0457de3b54dedfee59667062f4b to your computer and use it in GitHub Desktop.
简易 _.set & _.get
const setter = (obj, key, value) => {
const keys = key.split(".");
const pres = keys.slice(0, -1);
const last = keys[keys.length - 1];
const deepObj =
keys.length === 1
? obj
: pres.reduce((curObj, curKey) => {
// eslint-disable-next-line no-param-reassign
if (!curObj[curKey]) curObj[curKey] = {};
return curObj[curKey];
}, obj);
deepObj[last] = value;
return obj;
};
const getter = (obj, key) => {
const keys = key.split(".");
const value = keys.reduce((curObj, curKey) => curObj[curKey], obj);
return value;
};
const obj = {};
setter(obj, "person.name", "jc");
setter(obj, "person.age", 18);
// { person: { name: 'jc', age: 18 } }
console.log(obj);
const age = getter(obj, "person.age");
// 18
console.log(age);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment