Fork me on GitHub

获取对象任意层级属性值

获取一个对象不论多少层级的属性值,如有多个只取一个,不存在则返回undefined

案例:

let x = { a: { b: { c: { d: 1 } } } };
Object.prototype.getObjVal = function(key) {
  const _ = (obj) => {
    const keys = Object.keys(obj)
    const len = keys.length
    for (let i = 0; i < len; i++) {
      const k = keys[i]
      const val = obj[k]
      if (key === k) {
        return val
      } else if (Object.prototype.toString.call(val) === '[object Object]') {
        let res = _(val)
        if (res !== undefined) {
          return res
        }
      }
    }
  }
  return _(this)
}
console.log(x.getObjVal('a')) // { b: { c: { d: 1 } } }
console.log(x.getObjVal('c')) // { d: 1 }
console.log(x.getObjVal('d')) // 1
console.log(x.getObjVal('g')) // undefined

该方法已发布npm包get-obj-deep-val