跳到主要内容

get

2024年04月08日
柏拉文
越努力,越幸运

一、认识


二、实现


2.1 Bolawen reduce

function get(object, path, defaultValue) {
const pathRegExp = /[,\[\].]+?/;
const keys = Array.isArray(path)
? path
: path.split(pathRegExp).filter(Boolean);

return keys.reduce((value, key) => {
if (
value &&
typeof value === "object" &&
Object.prototype.hasOwnProperty.call(value, key)
) {
return value[key];
} else {
return defaultValue;
}
}, object);
}

测试代码

const object = { 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"));

2.2 Bolawen for……of

function get(object, path, defaultValue) {
const pathRegExp = /[,\[\].]+?/;
const keys = Array.isArray(path)
? path
: path.split(pathRegExp).filter(Boolean);

for (const key of keys) {
if (
object &&
typeof object === "object" &&
Object.hasOwnProperty.call(object, key)
) {
object = object[key];
} else {
return defaultValue;
}
}

return object;
}

测试代码

const object = { 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"));