JS Json 中获取 key 带. 点里面的值

平时后台会给一个key值找指定的key。如'user.name'其实就是要找JSON 里面的user,然后再找user里面的name。并不是直接key等于JSON里面的user.name;

个人的方法是:

   function getValue(obj, key) {
            let keyArr = key.split(".");
            if (typeof obj == "object") {
                let o = {};
                for (let index = 0; index < keyArr.length; index++) {
                    o = index === 0 ? obj[keyArr[index]] : o[keyArr[index]];
                }
                return o;
            }
            return obj;
        }

用法如下

        let obj = { a: { b: { c: "this is  c" } } };
        console.log(getValue(obj, "a.b.c")); //this is  c

注:这只是JSON 里面找多层的带点KEY值,不适用于其它

原文地址:https://www.cnblogs.com/huzhuhua/p/15337512.html