Javascript将集合代理到单个对象 [英] Javascript proxy a collection to single object
本文介绍了Javascript将集合代理到单个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我以前从未使用过Proxy,但是我认为应该可以将对象集合合并"到单个对象中. 它必须保持活动"状态,因为原始字段将对其执行值更改.
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 will have value changes performed on them.
在此阶段忽略按键碰撞:
Ignore key collisions at this stage:
给出:
const fields = [{
name: 'hello',
value: 1
},{
name: 'goodbye',
value : 2
}];
输出:
const proxy = { hello:1 , goodbye :2 }
我绝对需要能够使用for in
遍历代理对象.
I definitely need to be able to iterate over the proxied object with a for in
.
已在此处启动笔,但距离还很远: https://codepen.io/anon/pen/mMRaKw?editors=1111
Have start a pen here, but haven't got very far: https://codepen.io/anon/pen/mMRaKw?editors=1111
有可能吗?
推荐答案
我认为您正在寻找类似的东西:
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;
return true;
}
return false;
}
};
let prox = new Proxy(fields, handler);
console.log('flat obj', JSON.stringify(prox.flatten))
// update original
fields[0].value=10;
// change reflected in proxy
console.log('flatten.hello',prox.flatten.hello);
// update proxy
prox.goodbye = 200;
// change reflected in original
console.log('original', fields[1].value)
这篇关于Javascript将集合代理到单个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文