Skip to content Skip to sidebar Skip to footer

Javascript Proxy A Collection To Single Object

I've never used Proxy before, but I think it should be possible to 'merge' an collection of objects into a single object. It needs to remain 'live' because the original fields wil

Solution 1:

Here is a solution with the Proxy target as an empty object (if the Array is proxied, the for in will iterate numbered entries).

const fields = [{name: 'hello',value: 1}, { name: 'goodbye', value: 2}];

let handler = {
  get: function(target, name) {
      var f = fields.find(f => f.name === name);
      return f && f.value;
  },
  ownKeys: function(target) {
      return fields.map(f => f.name);
  },
  getOwnPropertyDescriptor: function(target, prop) {
    return { configurable: true, enumerable: true };
  }
};

let prox = newProxy({}, handler);

// update original
fields[0].value=10;
// change reflected in proxyconsole.log('proxy.hello',prox.hello);

for( let i in prox ){
  console.log(i)
  console.log(prox[i])
}
console.log(prox)

Solution 2:

I think you are looking for something like:

const fields = [{name: 'hello',value: 1}, { name: 'goodbye', value: 2}];

let handler = {
  get: function(target, name) {
    if (name === 'flatten') {    
      return target.reduce((a, c) => {
        a[c.name] = c.value;
        return a
      }, {});
    } else {
      return target[name];
    }
  },
   set: function(target, prop, value) {
      let obj = target.find(o => o.name === prop);
      if(obj) {        
         obj.value = value;
         returntrue;
      }
      returnfalse;
      
   }
};

let prox = newProxy(fields, handler);

console.log('flat obj', JSON.stringify(prox.flatten))

// update original
fields[0].value=10;
// change reflected in proxyconsole.log('flatten.hello',prox.flatten.hello);
// update proxy
prox.goodbye = 200;
// change reflected in originalconsole.log('original', fields[1].value)

Post a Comment for "Javascript Proxy A Collection To Single Object"