Javascript 获取用于访问对象中深度嵌套属性的所有键
我遇到了一个有趣的场景,在这个场景中,我需要确切地知道哪些键用于访问封装在代理中的对象中的深度嵌套属性 例如:Javascript 获取用于访问对象中深度嵌套属性的所有键,javascript,ecmascript-6,Javascript,Ecmascript 6,我遇到了一个有趣的场景,在这个场景中,我需要确切地知道哪些键用于访问封装在代理中的对象中的深度嵌套属性 例如: form.user.address.city 其中包装表单: const form = new Proxy(source, ...) 在代理的集合陷阱中,是否可能知道城市嵌套在地址下,而地址嵌套在用户下 我不想做这样的事情: const keys = [] set(target, prop, value, receiver) { if (typeof target[prop]
form.user.address.city
其中包装表单
:
const form = new Proxy(source, ...)
在代理的集合陷阱中,是否可能知道城市嵌套在地址下,而地址嵌套在用户下
我不想做这样的事情:
const keys = []
set(target, prop, value, receiver) {
if (typeof target[prop] === 'object') keys.push(prop)
}
公平地说,实际用例稍微复杂一些
表单
实际上代表了vuex
存储中的一个模块
最初,表单只有父级键和值对,并表示来自其他模块的字段集合,这些字段可用于防止更改vuex存储中的数据
因此,这是完美的:
const form = new Proxy(this.$store.getters['user'], {
get: (target, prop) => {
return _get(target, prop, undefined)
},
set: (target, prop, value) => {
this.$store.commit('user/SET_VALUE', { [prop] : value })
return true
}
})
现在,这非常有效,因为它使v-model
模式能够使用:
v-model="form.first_name"
而且我不必更改商店中的用户
,将所有更改范围限定为商店中的一个简单表单
模块
这种方法的复杂性现在已经增加了十倍,并且这种方法已经在许多地方使用,但是现在我需要修改深度嵌套的属性
这是我的问题的根本原因
进一步阐述--
我还实现了一种使用嵌套代理的模式,这并没有解决我的问题,因为它只向我揭示了嵌套对象的属性,例如,get
陷阱变成:
recursiveProxyGetter (target, prop) => {
if (typeof target[prop] === 'object' && target[prop] !== null) {
return new Proxy(target[prop], this.recursiveProxy)
}
return target[prop]
},
recursiveProxySetter(target, prop, value) => {
if (typeof target[prop] === 'object' && target[prop] !== null) {
return new Proxy(target[prop], this.recursiveProxy)
}
this.updateFormValue(prop, value)
return true
}
而设置
陷阱变成:
recursiveProxyGetter (target, prop) => {
if (typeof target[prop] === 'object' && target[prop] !== null) {
return new Proxy(target[prop], this.recursiveProxy)
}
return target[prop]
},
recursiveProxySetter(target, prop, value) => {
if (typeof target[prop] === 'object' && target[prop] !== null) {
return new Proxy(target[prop], this.recursiveProxy)
}
this.updateFormValue(prop, value)
return true
}
其中,recursiveProxy
被定义为my mixin上的一个简单属性:
recursiveProxy: any = {
get: this.recursiveProxyGetter,
set: this.recursiveProxySetter
}
并且表单被如此初始化:
form: {... a bunch of typescript unions} = new Proxy(this.$store.getters['user'], this.recursiveProxy)
我非常怀疑。如果他们写u=form.user;x=美国地址城市代码>?表单
代理需要时间机器才能知道结果稍后将用于访问地址
和城市
属性。但是,当您编写form.user.address.city
时,内部实际上就是这样发生的。您可能用了错误的方法。您想解决的实际问题是什么?您认为需要此解决方案吗?@Barmar请查看我的更新。它比我提供的psuedo代码要复杂一些。我认为您还需要为嵌套对象实现代理。我非常怀疑。如果他们编写u=form.user;x=美国地址城市代码>?表单
代理需要时间机器才能知道结果稍后将用于访问地址
和城市
属性。但是,当您编写form.user.address.city
时,内部实际上就是这样发生的。您可能用了错误的方法。您想解决的实际问题是什么?您认为需要此解决方案吗?@Barmar请查看我的更新。它比我提供的psuedo代码要复杂一些。我认为您还需要为嵌套对象实现代理。