_.get()
是 Lodash 库中一个非常实用的方法,用于安全地访问嵌套对象的属性。它允许你通过路径字符串或数组来获取嵌套对象中的值,而无需手动检查每一层是否存在。
_.get(object, path, [defaultValue])
object
: 要检索的对象path
: 要获取属性的路径,可以是字符串或数组[defaultValue]
: 可选,如果解析值是 undefined,则返回此值const _ = require('lodash');
const user = {
name: 'John',
address: {
street: '123 Main St',
city: 'New York'
}
};
// 安全访问嵌套属性
console.log(_.get(user, 'address.city')); // 'New York'
console.log(_.get(user, 'address.zipCode')); // undefined
console.log(_.get(user, 'address.zipCode', '10001')); // '10001' (默认值)
console.log(_.get(user, ['address', 'city'])); // 'New York'
const complexObj = {
a: {
b: {
c: [
{ d: 1 },
{ d: 2 }
]
}
}
};
console.log(_.get(complexObj, 'a.b.c[1].d')); // 2
console.log(_.get(complexObj, ['a', 'b', 'c', '1', 'd'])); // 2
原因:路径字符串格式不正确,如多余的.
或[]
解决:确保路径格式正确,或使用数组路径
// 错误示例
_.get(obj, 'a..b'); // 多余的点
_.get(obj, 'a[b]'); // 应该用 a.b 或 a[b]
// 正确示例
_.get(obj, 'a.b');
_.get(obj, ['a', 'b']);
原因:在大型对象或频繁调用时可能有性能影响
解决:对于性能关键路径,可以考虑缓存结果或使用原生代码
// 如果需要频繁访问同一路径
const getCity = obj => _.get(obj, 'address.city');
console.log(getCity(user));
原因:ES2020 引入了可选链操作符?.
,功能类似但有区别
解决:了解两者差异,根据场景选择
// 使用可选链
console.log(user?.address?.city);
// _.get 优势在于支持动态路径和默认值
const path = 'address.city';
console.log(_.get(user, path, 'Unknown'));
如果你不想引入整个 Lodash,可以使用类似的独立实现:
function get(obj, path, defaultValue) {
const pathArray = Array.isArray(path) ? path : path.split(/[\.\[\]]/).filter(Boolean);
let result = obj;
for (const key of pathArray) {
result = result?.[key];
if (result === undefined) return defaultValue;
}
return result ?? defaultValue;
}
_.get()
是处理 JavaScript 中嵌套对象访问的强大工具,特别适合处理不确定结构的对象数据。
没有搜到相关的文章