Search code examples
reactjsuse-statearray-merge

Merge two arrays using use state hook in React


First of all, I use React.js in my project. I want to merge two arrays using use state hook. I have two arrays. The first array is

[
  {
    "id": 1,
    "count": "2"
  },
  {
    "id": 2,
    "count": "1"
  }
  {
    "id": 3,
    "count": "1"
  }
  {
    "id": 4,
    "count": "1"
  }
  {
    "id": 5,
    "count": "1"
  },
]

And the second array is

[
  {
    "id": 1,
    "name": "Laptop"
  },
  {
    "id": 2,
    "name": "SSD"
  },
  {
    "id": 3,
    "name": "Keyboard"
  },
  {
    "id": 4,
    "name": "Mouse"
  },
  {
    "id": 5,
    "name": "Speaker"
  }
]

And I want to merge these arrays according to their mutual id. The result should be something like this,

[
  {
    "id": 1,
    "count": "2",
    "name": "Laptop"
  },
  {
    "id": 2,
    "count": "1",
    "name": "SSD"
  },
  {
    "id": 3,
    "count": "1",
    "name": "Keyboard"
  },
  {
    "id": 4,
    "count": "1",
    "name": "Mouse"
  },
  {
    "id": 5,
    "count": "1",
    "name": "Speaker"
  }
]

How can I merge these arrays?


Solution

  • Try like this:

    const A = [ { id: 1, count: "2", }, { id: 2, count: "1", }, { id: 3, count: "1", }, { id: 4, count: "1", }, { id: 5, count: "1", }, ]; const B = [ { id: 1, name: "Laptop", }, { id: 2, name: "SSD", }, { id: 3, name: "Keyboard", }, { id: 4, name: "Mouse", }, { id: 5, name: "Speaker", }, ];
    
    const output = A.map((itemA) => ({
      ...itemA,
      ...B.find((itemB) => itemB.id === itemA.id),
    }));
    
    console.log(output);