2 回答

TA貢獻(xiàn)1817條經(jīng)驗 獲得超6個贊
你必須小心改變你的對象。最好深度克隆您的對象和數(shù)組。
這是編寫代碼的另一種方法:
const allData = [];
for (let i = 0; i < allDetails.length; i++) {
const detail = allDetails[i];
const cells = [];
for (let j = 0; j < baseObj.cells.length; j++) {
const cell = {...baseObj.cells[j]};
switch (cell.key) {
case 'id':
cell.value = detail.id;
break;
case 'name':
cell.value = detail.name;
break;
}
cells.push(cell)
}
const row = {objKey: detail.objKey, index: i + 1, cells};
allData.push(row);
}

TA貢獻(xiàn)1993條經(jīng)驗 獲得超6個贊
您的問題在于:
row.cells = Object.assign([], baseObj.cells);
這會對數(shù)組進(jìn)行淺表復(fù)制,這意味著其中的對象baseObj不會被復(fù)制,并且在每次迭代時都引用相同的對象引用。您可以通過克隆對象來解決此問題,這可以通過使用以下方法來實現(xiàn):
row.cells = baseObj.cells.map(o => ({...o}));
你也在設(shè)置row.key = detail.objKey,當(dāng)這確實應(yīng)該是row.objectKey = detail.objKey
請參閱下面的示例:
const baseObj = {
objKey: '',
index: 1,
cells: [{
key: 'id',
value: ''
},
{
key: 'name',
value: ''
}
]
};
const allDetails = [{
objKey: '876',
name: 'abc',
id: '123',
address: '123abc'
},
{
objKey: '098',
name: 'def',
id: '456',
address: '456def'
},
];
const allData = [];
for (let i = 0; i < allDetails.length; i++) {
const detail = allDetails[i];
const row = Object.assign({}, baseObj);
row.cells = baseObj.cells.map(o => ({...o}));
row.objKey = detail.objKey;
row.index = i + 1;
for (let j = 0; j < row.cells.length; j++) {
const cell = row.cells[j];
switch (cell.key) {
case 'id':
cell.value = detail.id;
break;
case 'name':
cell.value = detail.name;
break;
}
}
allData.push(row);
};
console.log(allData);
上述問題的另一種解決方案是使用.map()構(gòu)建一個新對象,我們從基礎(chǔ)對象中獲取/借用屬性,并將任何重疊的屬性替換為當(dāng)前迭代對象中的屬性:
const baseObj = { objKey: '', index: 1, cells: [ { key: 'id', value: '' }, { key: 'name', value: '' } ] }; const allDetails = [ { objKey: '876', name: 'abc', id: '123', address: '123abc' }, { objKey: '098', name: 'def', id: '456', address: '456def' }, ];
const result = allDetails.map(({objKey, address, ...r}, index) => ({
...baseObj,
objKey,
index: index+1,
cells: baseObj.cells.map(o => ({...o, value: r[o.key]}))
}));
console.log(result);
添加回答
舉報