I'm not using the immutable library and I'm working on it.
I want to update the key and value values of mapTable without changing the constant of PRICE_OPTION2_STATE.
I'd appreciate it if you could tell me how. I have posted the results of the problem and the results I want.
//my code
tableData['option2Price'] = 50000;
const mapCopy = { ...copyState };
let tableCopy = { ...mapCopy[currentTableIndex].mapTable[findTableIndex] };
tableCopy = tableData;
mapCopy.tableCopy = tableCopy;
// problem
console.log(PRICE_OPTION2_STATE);
// initstate
const PRICE_OPTION2_STATE = [
{
id: 1,
option2Name: '',
option2LeftSelect: 'sell',
mapTable: [
{
tableId: 1,
flag: true,
option2Value: '',
option2Price: '',
discountInput2: '',
discountOption2: 'won',
option2Payment: '',
option2Tax: '',
option2settlementAmount: '',
option2RightSelect: 'sell',
},
],
},
];
PRICE_OPTION2_STATE => problem console result
[
{
id: 1,
option2Name: '',
option2LeftSelect: 'sell',
mapTable: [
{
tableId: 1,
flag: true,
option2Value: '',
option2Price: '',
discountInput2: '',
discountOption2: 'won',
option2Payment: '50000',
option2Tax: '',
option2settlementAmount: '',
option2RightSelect: 'sell',
},
],
},
]
result i want
[
{
id: 1,
option2Name: '',
option2LeftSelect: 'sell',
mapTable: [
{
tableId: 1,
flag: true,
option2Value: '',
option2Price: '',
discountInput2: '',
discountOption2: 'won',
option2Payment: '',
option2Tax: '',
option2settlementAmount: '',
option2RightSelect: 'sell',
},
],
},
]
CodePudding user response:
I'll assume copyState
is a reference to PRICE_OPTION2_STATE
or at least is some sort of (shallow) copy of it. So to copy it, you should:
- not use object spread notation at the top level, since it is an array.
- not leave it at a shallow copy, but copy it deeply. So you'll also need to map the inner array and copy the objects it has.
Here is some inspiration:
// Assuming copyState has the structure of PRICE_OPTION2_STATE
// Get a deep copy
const mapCopy = copyState.map(({mapTable, ...rest}) => ({
...rest,
mapTable: mapTable.map(obj => ({...obj}))
}));
// Now this assignment will not impact copyState / PRICE_OPTION2_STATE
mapCopy[currentTableIndex].mapTable[findTableIndex] = tableCopy;