-
一只萌萌小番薯
您需要根据索引动态创建键,如果键对应的值存在,则需要替换该值。这可以在不使用spread syntax和改变状态的情况下实现Array.prototype.mapvar 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);
-
莫回无
您可以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);
-
皈依舞
使用 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)