1

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!

labilouser
  • 177
  • 1
  • 2
  • 9
  • The spread operator just places the data side-by-side in an array. A simple loop matching the IDs to merge the data would probably be the simplest approach. – SimpleProgrammer Aug 13 '21 at 09:12

3 Answers3

1

Maybe you can use it this way.

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"
  }
]

const mergeArrays = (firstArray = [], arr2 = []) => {
  let res = [];
  res = firstArray.map(obj => {
    const index = secondArray.findIndex(el => el["id"] == obj["id"]);

    const {
      address
    } = index !== -1 ? secondArray[index] : {};
    const {
      postcode
    } = index !== -1 ? secondArray[index] : {};

    return {
      ...obj,
      address,
      postcode
    };
  });
  return res;
};


console.log(mergeArrays(firstArray, secondArray))
0

with forEach you can achieve like below.

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"
    }
]

firstArray.forEach(a=>{
 secondArray.forEach(b=>{
   if(b.id===a.id){
     a.address = b.address
     a.postcode = b.postcode
   }
 })
})

console.log(firstArray)
Prakash Bhosale
  • 227
  • 1
  • 7
0

This will give you the required output although order is not guaranteed for the merged elements since we are using map to merge data based on id.

function mergeArrays(arrayOne, arrayTwo) {
  const idMap = {};
  firstArray.forEach(data => {
    idMap[data.id] = idMap[data.id] || {id: data.id};
    idMap[data.id] = {...idMap[data.id], ...data};
  });
  secondArray.forEach(data => {
    idMap[data.id] = idMap[data.id] || {id: data.id};
    idMap[data.id] = {...idMap[data.id], ...data};
  });
  return Object.keys(idMap).map(id => idMap[id]);
}
Akash
  • 103
  • 8