3 回答
![?](http://img1.sycdn.imooc.com/54584cde0001d19202200220-100-100.jpg)
TA贡献1795条经验 获得超7个赞
您需要根据索引动态创建键,如果键对应的值存在,则需要替换该值。这可以在不使用spread syntax和改变状态的情况下实现Array.prototype.map
var state = {
editValue0: "Australia123",
editValue1: "Europe123",
editValue2: "Asia123",
editValue3: "Africa123",
selectedQuestion: [
{
id: 1,
options: [
{
opt: "Australia"
},
{
opt: "Europe"
},
{
opt: "Asia"
},
{
opt: "Africa"
}
]
}
]
}
const newState = {
...state,
selectedQuestion: state.selectedQuestion.map((data) => {
return {
...data,
options: data.options.map((opt, i) => {
const key = `editValue${i}`;
return {
opt: state[key]? state[key]: opt.opt
}
})
}
})
}
console.log(newState);
![?](http://img1.sycdn.imooc.com/5458662500019a7c02200220-100-100.jpg)
TA贡献1865条经验 获得超7个赞
您可以forEach与索引一起使用来分配值:
var state2 = {
editValue0: "Australia123",
editValue1: "Europe123",
editValue2: "Asia123",
editValue3: "Africa123",
selectedQuestion: [{
id: 1,
options: [{
opt: "Australia"
},
{
opt: "Europe"
},
{
opt: "Asia"
},
{
opt: "Africa"
}
]
}]
};
state2.selectedQuestion[0].options.forEach((e, i) => {state2['editValue' + i] = e.opt;});
console.log(state2);
![?](http://img1.sycdn.imooc.com/545861b80001d27c02200220-100-100.jpg)
TA贡献1851条经验 获得超3个赞
使用 forEach 循环
var state2 = {
editValue0: "Australia123",
editValue1: "Europe123",
editValue2: "Asia123",
editValue3: "Africa123",
selectedQuestion: [{
id: 1,
options: [{
opt: "Australia"
},
{
opt: "Europe"
},
{
opt: "Asia"
},
{
opt: "Africa"
}
]
}]
}
state2.selectedQuestion.forEach(function(e){e.options.forEach(function(k,l){
state2["editValue"+l]=k.opt;
})})
console.log(state2)
添加回答
举报