英文:
Update nested property of object in an array
问题
我有一个类似这样的对象:
data: {
users: [
{
id: "someString",
liquidityPositions: [
{
balance: "someString",
pair: {
id: "someString",
reserve0: "someString",
reserve1: "someString",
token0: {
id: "someString"
},
token1: {
id: "someString"
},
}
},
...
]
}
]
}
我试图修改token0
和token1
的属性,以包括额外的属性symbol
:
let updated = myObj.data.users[0].liquidityPositions.map(
(liquidityPosition) => ({
...liquidityPosition,
token0: {
...liquidityPosition.token0,
symbol: "yourSymbolForToken0"
},
token1: {
...liquidityPosition.token1,
symbol: "yourSymbolForToken1"
}
})
);
如何在保留其他所有内容的情况下向token0
和token1
添加新属性?
英文:
I have an object that looks like this:
data: {
users: [
{
id: "someString",
liquidityPositions: [
{
balance: "someString",
pair: {
id: "someString",
reserve0: "someString",
reserve1: "someString",
token0: {
id: "someString"
},
token1: {
id: "someString"
},
}
},
...
]
}
]
}
I'm trying to change the property of token0
and token1
to include an extra property symbol
:
let updated = myObj.data.user[0].liquidityPositions.map(
(liquidityPosition) => ({
...balance,
//I'm not sure how to update here
How can I add a new property to token0
and token1
while preserving everything else?
答案1
得分: 2
我会这样做。
data.users[0].liquidityPositions.map(({pair, ...rest}) => {
const token0 = {...pair.token0, symbol: 'asdf'};
const token1 = {...pair.token1, symbol: 'qwerty'};
return {...rest, pair: {...pair, token0, token1}};
});
英文:
I'd do it like this.
data.users[0].liquidityPositions.map(({pair, ...rest}) => {
const token0 = {...pair.token0, symbol: 'asdf'};
const token1 = {...pair.token1, symbol: 'qwerty'};
return {...rest, pair: {...pair, token0, token1}};
});
答案2
得分: 1
这不太简洁,但似乎可以工作
let updated = data.users[0].liquidityPositions.map((liquidityPosition) => {
let oldPair = liquidityPosition.pair;
return {
...liquidityPosition,
pair: {
...oldPair,
token0: {
...oldPair.token0,
id: "newString"
},
token1: {
...oldPair.token1,
id: "newString"
}
}
};
});
你也可以选择内联旧引用,如果你愿意
let updated = data.users[0].liquidityPositions.map((liquidityPosition) => ({
...liquidityPosition,
pair: {
...liquidityPosition.pair,
token0: {
...liquidityPosition.pair.token0,
id: "newString"
},
token1: {
...liquidityPosition.pair.token1,
id: "newString"
}
}
}));
英文:
This is not so concise, but it seems to work
let updated = data.users[0].liquidityPositions.map((liquidityPosition) => {
let oldPair = liquidityPosition.pair
return {
...liquidityPosition,
pair: {
...oldPair,
token0: {
...oldPair.token0,
id: "newString"
},
token1: {
...oldPair.token1,
id: "newString"
}
}
}
})
Also you can just inline the old reference, if you want
let updated = data.users[0].liquidityPositions.map((liquidityPosition) => ({
...liquidityPosition,
pair: {
...liquidityPosition.pair,
token0: {
...liquidityPosition.pair.token0,
id: "newString"
},
token1: {
...liquidityPosition.pair.token1,
id: "newString"
}
}
}))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论