Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all objects stored inside proxy?

Tags:

javascript

Let's assume that this is the proxy.

var target = {};
var p = new Proxy(target, {});
p.a = 1; 
p.b = 2;

I know I can access the objects via console.log(p.a) and console.log(p.b) but how do I programatically fetch all the objects stored?

Disclaimer: I'm a Javascript noob but I did read the documentation at: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#Examples but it wasn't really clear.

like image 626
Abhijeet Rastogi Avatar asked Dec 07 '25 06:12

Abhijeet Rastogi


2 Answers

var target = {};
var p = new Proxy(target, {});
p.a = 1; 
p.b = 2;

console.log(p);
// {
//   "a": 1,
//   "b": 2
// }

console.log(Object.keys(p));
// ["a", "b"]


// only in ES6 and above:
console.log(Object.values(p));
// [1, 2]

// In older JS versions:
for(var key of Object.keys(p)) {
  console.log(p[key]);
}
// 1
// 2
like image 107
Randy Avatar answered Dec 09 '25 19:12

Randy


What you are looking for is the for .. in loop

for (var property in p) {
    console.log(p[property]);
}

More details here

like image 27
Mansuro Avatar answered Dec 09 '25 19:12

Mansuro