我正在尝试嵌套这些解构赋值,以便分别初始化为context1
和:context2
market[pair.context]
market[pair.target]
// set market to this[pair.market] or empty object
const {
[pair.market]: market = {},
} = this;
// set context1 to market[pair.context] or empty object
// set context2 to market[pair.target] or empty object
const {
[pair.context]: context1 = {},
[pair.target]: context2 = {},
} = market;
我认为这种正确的方法是这样的:
const {
[pair.context]: context1 = {},
[pair.target]: context2 = {},
} = {
[pair.market]: market = {},
} = this;
但是,当market[pair.context]
或market[pair.target]
已经存在时,它的行为似乎并不像预期的那样。
我对解构还很陌生,但我决心掌握它。为什么会这样,我如何结合前两个解构?
测试相关代码:
const pair1 = {
context: 'A',
target: 'B',
market: 'MARKET1',
price: '0.1',
};
const pair2 = {
context: 'A',
target: 'C',
market: 'MARKET1',
price: '1',
};
const pair3 = {
context: 'C',
target: 'B',
market: 'MARKET2',
price: '0.1',
};
// markets
function addPair (pair) {
const {
[pair.market]: market = {},
} = this;
const {
[pair.context]: context1 = {},
[pair.target]: context2 = {},
} = market;
this[pair.market] = {
...market,
[pair.context]: {
...context1,
[pair.target]: {
price: +(pair.price),
},
},
[pair.target]: {
...context2,
[pair.context]: {
price: +(1 / pair.price),
},
},
};
}
const markets = {};
addPair.call(markets, pair1);
addPair.call(markets, pair2);
addPair.call(markets, pair3);
console.log(markets);