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:
JavaScript
x
36
36
1
const currentData = [{
2
FIRST_NAME: 'ABC',
3
MIDDLE_NAME: 'DEF',
4
LAST_NAME: 'GHI'
5
}]
6
7
const historicalData = [{
8
FIRST_NAME: 'ABC1',
9
MIDDLE_NAME: 'DEF1',
10
LAST_NAME: 'GHI1'
11
}, {
12
FIRST_NAME: 'ABC2',
13
MIDDLE_NAME: 'DEF2',
14
LAST_NAME: 'GHI2'
15
}, {
16
FIRST_NAME: 'ABC3',
17
MIDDLE_NAME: 'DEF3',
18
LAST_NAME: 'GHI3'
19
}]
20
21
const rowDataKeys = Object.keys(currentData[0])
22
23
const rowData = rowDataKeys.map((i) => {
24
const resp = historicalData.map((j, index) => {
25
return {
26
[`history${index+1}`]: historicalData[index][i]
27
}
28
})
29
return {
30
field: i,
31
current: currentData[0][i],
32
resp
33
}
34
})
35
36
console.log(rowData)
Expected Output:
JavaScript
1
20
20
1
[{
2
field: 'FIRST_NAME',
3
current: 'ABC',
4
history1: 'ABC1',
5
history2: 'ABC2',
6
history3: 'ABC3'
7
}, {
8
field: 'MIDDLE_NAME',
9
current: 'DEF',
10
history1: 'DEF1',
11
history2: 'DEF2',
12
history3: 'DEF3'
13
}, {
14
field: 'LAST_NAME',
15
current: 'GHI',
16
history1: 'GHI1',
17
history2: 'GHI2',
18
history3: 'GHI3'
19
}]
20
Advertisement
Answer
The type of resp in the code snippet before is an array of objects.
JavaScript
1
6
1
const resp = historicalData.map((j, index) => {
2
return {
3
[`history${index+1}`]: historicalData[index][i]
4
}
5
});
6
You likely want the type to be an object directly.
You can use Array.reduce for this:
JavaScript
1
35
35
1
const currentData = [{
2
FIRST_NAME: 'ABC',
3
MIDDLE_NAME: 'DEF',
4
LAST_NAME: 'GHI'
5
}]
6
7
const historicalData = [{
8
FIRST_NAME: 'ABC1',
9
MIDDLE_NAME: 'DEF1',
10
LAST_NAME: 'GHI1'
11
}, {
12
FIRST_NAME: 'ABC2',
13
MIDDLE_NAME: 'DEF2',
14
LAST_NAME: 'GHI2'
15
}, {
16
FIRST_NAME: 'ABC3',
17
MIDDLE_NAME: 'DEF3',
18
LAST_NAME: 'GHI3'
19
}]
20
21
const rowDataKeys = Object.keys(currentData[0])
22
23
const rowData = rowDataKeys.map((i) => {
24
const resp = historicalData.reduce((acc, j, index) => ({
25
acc,
26
[`history${index+1}`]: historicalData[index][i],
27
}), {})
28
return {
29
field: i,
30
current: currentData[0][i],
31
resp
32
}
33
})
34
35
console.log(rowData)