使用点表示法将嵌套属性添加到不存在的属性

asn*_*aeb 3 javascript object

在 javascript 中,我们可以使用点表示法向对象添加新属性

const obj = {}
obj.a = "hello"

console.log(obj) // prints { a: "hello" }
Run Code Online (Sandbox Code Playgroud)

但是,使用点表示法,无法将属性添加到尚不存在的对象

obj.a.b = "hello" // <-- cannot set properties of undefined (setting 'b')
obj.a = { b: "hello" } // <-- OK
Run Code Online (Sandbox Code Playgroud)

我想实现这种行为

const obj = {}
obj.a.b = "hello"

console.log(obj) // prints { a: { b: "hello" } }
Run Code Online (Sandbox Code Playgroud)

我的想法

我能想到的唯一可以接近这个的就是使用代理

const obj = new Proxy({}, {
    set(target, key, receiver) {
        // if a.b could make it here before the error is thrown, i'd handle this
       // btw, this means that "key" should contain [a,b] which is not how this works.
    }
})

obj.a.b = "hello"
Run Code Online (Sandbox Code Playgroud)

代理的想法无法工作,并且可能绝对没有办法像我问的那样改变 JS 的本机行为,但也许我错过了一些东西?

moc*_*cha 7

代理确实有效。您需要使用get陷阱而不是set

const obj = new Proxy({}, {
    get(target, key, receiver) {
        if (!(key in target)) return (target[key] = {});

        return Reflect.get(target, key);
    },
});

obj.a.b = "hello";

console.log(obj);
Run Code Online (Sandbox Code Playgroud)