Last active
January 1, 2021 06:44
-
-
Save JerryC8080/56e4b0457de3b54dedfee59667062f4b to your computer and use it in GitHub Desktop.
简易 _.set & _.get
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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