Obj.abc get value exception handling

In the usual development process, you will always encounter obj.a.b.ca method similar to passing to obtain the value contained in the deep layer of the object. However, if you encounter or are a, , , and other data types , an error will appear. Moreover, we often obtain data from the database through the backend. In this link, it is impossible to say that a similar situation will occur during the transfer process someday. Below we write the method by hand to prevent this from happening.bcnullundefined1'2'trueget

1. getFunction

let get = function (obj, path, defaultValue) {
    // 将路径拆分成数组
    let pathArr = path.split('.');
    // 默认是传入的值
    let currentValue = obj;
    for (let i = 1; i < pathArr.length; i++) {
        // 边界1:如果上一次值不是对象,或者为null,或者为undefined,直接返回默认值
        if (typeof currentValue !== 'object' || currentValue === null || currentValue === undefined) {
            return defaultValue;
        }
        // 当前路径
        let path = pathArr[i]
        // 当前key的数组
        let keys = Object.keys(currentValue)
        // 边界2:当前路径不在上一次值的keys中,直接返回默认值
        if (!keys.includes(path)) {
            return defaultValue;
        }
        // 获取当前路径下的值
        currentValue = currentValue[path];
    }
    return currentValue;
}
复制代码

2. Test case

// 测试1
let obj1 = {
    a: [{
        b: {
            c: 3
        }
    }]
}
console.log(get(obj1, 'obj1.a.0.b.c', -1)) // 3
console.log(get(obj1, 'obj1.a.0.d.c', -1)) // -1
console.log(get(obj1, 'obj1.a.0.b.c.f', -1)) // -1

// 测试2
let obj2 = {
    a: {
        b: null
    }
}
console.log(get(obj2, 'obj2.a.b', -1)) // null
console.log(get(obj2, 'obj2.a.b.c', -1)) // -1
// 测试3
let obj3 = {
    a: {
        b: undefined
    }
}
console.log(get(obj3, 'obj3.a.b', -1)) // undefined
console.log(get(obj3, 'obj3.a.b.c', -1)) // -1
复制代码

Guess you like

Origin juejin.im/post/7190276911371665465