Mr. Snuffles
Mr. Snuffles

Reputation: 33

How to push to an array value in proxy object in Javascript

in normal object we can push to normal array value like obj.l =[]; obj.l.push("test")

Example.

var prxy =  new Proxy({} , {
get(target, name){
    return target[name]
}, 
set(target,name, value){
    target[name] = value; 
    return true;
}
})

prxy.h = {test : "test"}
>> {test: "test"}
prxy.h
>>{test: "test"}
prxy.h.push("test")
>>VM2724:1 Uncaught TypeError: prxy.h.push is not a function
at <anonymous>:1:8

Upvotes: 2

Views: 2896

Answers (1)

Lars Peterson
Lars Peterson

Reputation: 1508

You can't use array methods on an object. And there really wouldn't be a point here anyway. There's no reason to use push() when you can just append a value to an object:

prxy.h.someKey = someValue;

Or using a dynamic key:

var dynamicKey = "car";
prxy.h[dynamicKey] = someValue;

Upvotes: 5

Related Questions