简体   繁体   English

在 React 中使用 state 钩子合并两个 arrays

[英]Merge two arrays using use state hook in React

First of all, I use React.js in my project.首先,我在我的项目中使用 React.js。 I want to merge two arrays using use state hook.我想使用 state 钩子合并两个 arrays 。 I have two arrays.我有两个 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.我想根据他们的共同ID合并这些arrays。 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?如何合并这些 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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