Home > Mobile >  Merge two arrays using use state hook in React
Merge two arrays using use state hook in React

Time:09-03

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?

CodePudding user response:

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);

CodePudding user response:

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

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

const length = Math.max(arr1.length, arr2.length);
const result = [...Array(length).keys()].map(i => ({
  ...arr1[i],
  ...arr2[i]
}));

console.log(result);

  • Related