我有兩個具有相同鍵的物件陣列,我想將它們組合起來并創建一個新的物件陣列。我幾乎可以做對所有事情,但是當我想將它們分布在新陣列中時會出現問題。價差自動包含一個鍵值對,其中包含索引和我不想要的值。我錯過了什么?請指教。
這是我的實作:
const currentData = [{
FIRST_NAME: 'ABC',
MIDDLE_NAME: 'DEF',
LAST_NAME: 'GHI'
}]
const historicalData = [{
FIRST_NAME: 'ABC1',
MIDDLE_NAME: 'DEF1',
LAST_NAME: 'GHI1'
}, {
FIRST_NAME: 'ABC2',
MIDDLE_NAME: 'DEF2',
LAST_NAME: 'GHI2'
}, {
FIRST_NAME: 'ABC3',
MIDDLE_NAME: 'DEF3',
LAST_NAME: 'GHI3'
}]
const rowDataKeys = Object.keys(currentData[0])
const rowData = rowDataKeys.map((i) => {
const resp = historicalData.map((j, index) => {
return {
[`history${index 1}`]: historicalData[index][i]
}
})
return {
field: i,
current: currentData[0][i],
...resp
}
})
console.log(rowData)
預期輸出:
[{
field: 'FIRST_NAME',
current: 'ABC',
history1: 'ABC1',
history2: 'ABC2',
history3: 'ABC3'
}, {
field: 'MIDDLE_NAME',
current: 'DEF',
history1: 'DEF1',
history2: 'DEF2',
history3: 'DEF3'
}, {
field: 'LAST_NAME',
current: 'GHI',
history1: 'GHI1',
history2: 'GHI2',
history3: 'GHI3'
}]
uj5u.com熱心網友回復:
之前代碼片段中的 resp 型別是一個物件陣列。
const resp = historicalData.map((j, index) => {
return {
[`history${index 1}`]: historicalData[index][i]
}
});
您可能希望型別直接成為物件。
您可以為此使用Array.reduce :
const currentData = [{
FIRST_NAME: 'ABC',
MIDDLE_NAME: 'DEF',
LAST_NAME: 'GHI'
}]
const historicalData = [{
FIRST_NAME: 'ABC1',
MIDDLE_NAME: 'DEF1',
LAST_NAME: 'GHI1'
}, {
FIRST_NAME: 'ABC2',
MIDDLE_NAME: 'DEF2',
LAST_NAME: 'GHI2'
}, {
FIRST_NAME: 'ABC3',
MIDDLE_NAME: 'DEF3',
LAST_NAME: 'GHI3'
}]
const rowDataKeys = Object.keys(currentData[0])
const rowData = rowDataKeys.map((i) => {
const resp = historicalData.reduce((acc, j, index) => ({
...acc,
[`history${index 1}`]: historicalData[index][i],
}), {})
return {
field: i,
current: currentData[0][i],
...resp
}
})
console.log(rowData)
uj5u.com熱心網友回復:
陣列[a, b, c]作為物件分布在物件內部{ '0': a, '1': b, '2': c },索引為鍵,元素為值。您可以改為創建一個物件reduce。
const currentData = [{
FIRST_NAME: 'ABC',
MIDDLE_NAME: 'DEF',
LAST_NAME: 'GHI'
}]
const historicalData = [{
FIRST_NAME: 'ABC1',
MIDDLE_NAME: 'DEF1',
LAST_NAME: 'GHI1'
}, {
FIRST_NAME: 'ABC2',
MIDDLE_NAME: 'DEF2',
LAST_NAME: 'GHI2'
}, {
FIRST_NAME: 'ABC3',
MIDDLE_NAME: 'DEF3',
LAST_NAME: 'GHI3'
}]
const rowDataKeys = Object.keys(currentData[0])
const rowData = rowDataKeys.map((i) => {
const resp = historicalData.reduce((acc, j, index) => {
acc[`history${index 1}`] = historicalData[index][i];
return acc;
}, {})
return {
field: i,
current: currentData[0][i],
...resp
}
})
console.log(rowData)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/473532.html
標籤:javascript 数组
下一篇:映射Typescript通用陣列
