In React, I have two arrays of objects:
const [finalData, setFinalData] = useState([
{
id: '',
name: '',
salutation: '',
address: '',
postcode: ''
}
])
const firstArray = [
{
id: 1,
name: "Alex",
salutation: "Mr."
},
{
id: 2,
name: "Maria",
salutation: "Ms."
}
]
const secondArray = [
{
id: 1,
address: "Larch Retreat 31",
postcode: "123452"
},
{
id: 2,
address: "Lycroft Close 12D",
postcode: "123009"
}
]
What is the best way to merge the two arrays into a final set of data, an array of objects composed of data from the original arrays?
I have tried to create a function, that maps the combined first two arrays and create the new object:
const someFunction = () => {
const combinedArrays = [...firstArray, ...secondArray]
setFinalData(combinedArrays.map(object => {
return {
id: object.id,
name: object.name,
salutation: object.salutation,
address: object.address,
postcode: object.postcode
}
}))
}
but this is creating:
{id: 1, name: "Alex", salutation: "Mr.", address: undefined, postcode: undefined}
{id: 2, name: "Maria", salutation: "Ms.", address: undefined, postcode: undefined}
{id: 1, name: undefined, salutation: undefined, address: "Larch Retreat 31", postcode: "123452"}
{id: 2, name: undefined, salutation: undefined, address: "Lycroft Close 12D", postcode: "123009"}
Which is not fine, ideally should be:
{id: 1, name: "Alex", salutation: "Mr.", address: "Larch Retreat 31", postcode: "123452"}
{id: 2, name: "Maria", salutation: "Ms.", address: "Lycroft Close 12D", postcode: "123009"}
Thanks!