You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
/** * 实现lodash的_.get * lodash官方文档 * Gets the value at path of object. If the resolved value is undefined, * the defaultValue is returned in its place. * * Argumentsobject (Object): The object to query.path (Array|string): The path of the property to get.[defaultValue] (*): The value returned for undefined resolved values. * Returns(*): Returns the resolved value. * 官方示例var object = { 'a': [{ 'b': { 'c': 3 }}] };_.get(object, 'a[0].b.c');// => 3_.get(object, ['a', '0', 'b', 'c']);// => 3_.get(object, 'a.b.c', 'default');// => 'default' */classLodash{get(object,path,defaultValue=undefined){if(typeofobject!=="object"){thrownewError("first argument of get should be an object");}if(pathinstanceofArray){returnthis._keysReduce(object,path,defaultValue);}if(typeofpath==="string"){constkeys=path.split(/[\.|\[|\]]/).filter((key)=>Boolean(key));returnthis._keysReduce(object,keys,defaultValue);}}_keysReduce(object,path,defaultValue){returnpath.reduce((pre,cur)=>{if(typeofcur!=="string"){thrownewError("path should be an Array of Strings");}if(pre===undefined){returndefaultValue;}returnpre[cur];},object);}}const_=newLodash();constobject={a: [{b: {c: 3}}]};console.log(_.get(object,"a[0].b.c"));console.log(_.get(object,["a","0","b","c"]));console.log(_.get(object,"a.b.c","default"));
Activity
Genzhen commentedon Jun 23, 2020
在 js 中经常会出现嵌套调用这种情况,如 a.b.c.d.e,但是这么写很容易抛出异常。你需要这么写 a && a.b && a.b.c && a.b.c.d && a.b.c.d.e,但是显得有些啰嗦与冗长了。特别是在 graphql 中,这种嵌套调用更是难以避免。
这时就需要一个 get 函数,使用 get(a, 'b.c.d.e') 简单清晰,并且容错性提高了很多。
1)代码实现
2)代码实现
不考虑数组的情况
Genzhen commentedon Jun 23, 2020
huzedong2015 commentedon Aug 28, 2020
ES2020 可以链式 & 空值合并运算
data?.b?.[4] ?? 20
huzedong2015 commentedon Aug 28, 2020
path参数还有数组的可能
sh-tengfei commentedon Jan 13, 2021
newPath.replace(/[(\w)+]/g, ".$1"); 这里是否应该是 newPath.replace(/[(\d+)]/g, ".$1");
Xiaolong96 commentedon Mar 22, 2021
qzruncode commentedon Apr 14, 2021
fanerge commentedon May 17, 2021
jonny-wei commentedon May 18, 2021
Luoyuda commentedon Jun 10, 2021
Evllis commentedon Aug 11, 2021
Weibozzz commentedon Sep 9, 2021
改进版本
safarishi commentedon Oct 14, 2021
captain-kuan commentedon Dec 14, 2022
yaohui-li commentedon Aug 25, 2023
const getPath = (path) => {
const paths = [']', '[', '.']
if (Array.isArray(path)) return path;
return Array.from(path).filter((str) => !paths.includes(str))
};
const getObjectValue = (object, path, defaultValue) => {
const objectPath = getPath(path);
let target = object
let index = 0;
while (index < objectPath.length) {
target = target[objectPath[index++]];
if (target === undefined) break;
}
return index === objectPath.length ? target : defaultValue;
};
Kisthanny commentedon Mar 20, 2024
aaronxdd commentedon Sep 7, 2024
const obGet = (ob, path, defaltValue) => {
const kes = Array.isArray(path) ? path : path.split('.');
return kes.reduces((pre, current) => pre[current], ob) || defaltValue;
}