I have two arrays of objects with the same keys and I want to combine them and create a new array of objects. I am able to get almost everything right, but the issue occurs when I want to spread them inside the new array. The spread automatically includes a key value pair with the index and the value which is not what i want. What am I missing? Please advice.
This is my implementation:
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)
Expected Output:
[{
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'
}]
CodePudding user response:
An array [a, b, c]
is spread inside an object as object { '0': a, '1': b, '2': c }
with index as key and element as value. You can create an object with reduce
instead.
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)
CodePudding user response:
The type of resp in the code snippet before is an array of objects.
const resp = historicalData.map((j, index) => {
return {
[`history${index 1}`]: historicalData[index][i]
}
});
You likely want the type to be an object directly.
You can use Array.reduce for this:
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)