简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM