一种在不知道嵌套 js 对象中的路径的情况下访问属性的方法 [英] A way to access a property without knowing its path in a nested js object
问题描述
有没有办法在不知道路径的情况下访问对象中的嵌套属性?例如我可以有这样的东西
is there a way to access a nested property within an object without knowing its path? For instance I could have something like this
let test1 = {
location: {
state: {
className: 'myCalss'
}
}
};
let test2 = {
params: {
className: 'myCalss'
}
};
有没有巧妙的方法来提取"className
属性?我有一个解决方案,但它很丑陋,它只考虑了这两种情况,我想知道是否有更灵活的方法可以做
Is there neat way to 'extract' className
property?
I have a solution but it's pretty ugly, and it accounts just for this two cases, I was wondering if there is something more flexible I could do
推荐答案
这是创建嵌套属性 getter 的一种优雅的方法:
Here's a somewhat elegant approach to creating nested property getters:
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))
如果你想防止循环对象导致堆栈溢出,我建议使用 WeakSet
来跟踪迭代对象引用:
If you want to prevent cyclical objects from causing a stack overflow, I suggest using a WeakSet
to keep track of iterated object references:
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))
这篇关于一种在不知道嵌套 js 对象中的路径的情况下访问属性的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!