0

有没有办法在不知道其路径的情况下访问对象内的嵌套属性?例如我可以有这样的东西

let test1 = {
  location: {
    state: {
     className: 'myCalss'
    }
 }
};

let test2 = {
  params: {
    className: 'myCalss'
  }
};

有没有“提取”className财产的巧妙方法?我有一个解决方案,但它非常难看,它仅适用于这两种情况,我想知道是否有更灵活的方法可以做

4

2 回答 2

3

这是创建嵌套属性 getter 的一种优雅的方法:

const getProperty = property => {
  const getter = o => {
    if (o && typeof o === 'object') {
      return Object.entries(o)
        .map(([key, value]) => key === property ? value : getter(value))
        .filter(Boolean)
        .shift()
    }
  }

  return getter
}

const test1 = {
  location: {
    state: {
      className: 'test1'
    }
  }
}

const test2 = {
  params: {
    className: 'test2'
  }
}

const test3 = {}

const getClassName = getProperty('className')

console.log(getClassName(test1))
console.log(getClassName(test2))
console.log(getClassName(test3))

如果要防止循环对象导致堆栈溢出,我建议使用 aWeakSet来跟踪迭代对象引用:

const getProperty = property => {
  const getter = (o, ws = new WeakSet()) => {
    if (o && typeof o === 'object' && !ws.has(o)) {
      ws.add(o)
      return Object.entries(o)
        .map(([key, value]) => key === property ? value : getter(value, ws))
        .filter(Boolean)
        .shift()
    }
  }

  return getter
}

const test1 = {
  location: {
    state: {
      className: 'test1'
    }
  }
}

const test2 = {
  params: {
    className: 'test2'
  }
}

const test3 = {}
const test4 = {
  a: {
    b: {}
  }
}

test4.a.self = test4
test4.a.b.self = test4
test4.a.b.className = 'test4'

const getClassName = getProperty('className')

console.log(getClassName(test1))
console.log(getClassName(test2))
console.log(getClassName(test3))
console.log(getClassName(test4))

于 2018-06-06T23:11:22.523 回答
1

当然。试试这个。它递归地遍历对象并返回第一个匹配项。您可以for根据需要将循环配置为匹配全部或最后一个

let test1 = {
  location: {
    state: {
     className: 'myCalss'
    }
 }
};

let test2 = {
  params: {
    className: 'myCalss'
  }
};

function getClassName(obj) {
  if(typeof obj === "object" && 'className' in obj) {
    return obj.className
  }
  const keys = Object.keys(obj)
  for(let i = 0; i < keys.length; i++) {
    let key = keys[i]
    let res = getClassName(obj[key])
    if(res) return res
  }
  return null
}

console.log(getClassName(test1), getClassName(test2))

于 2018-06-06T22:59:59.463 回答