a543462378
2022-04-27 15:09
采纳率: 93.6%
浏览 40
已结题

react中如何把后端返回的数组合并入前端定义的数组

项目中前端自定义了数组1,然后访问后台接口获得数组二,要根据shipType参数把两个数组合并成一个

// 前端定义的数组1
const tableList = [
    { shipType: "0", useFrequency: 0, useDuration: 0, useAmount: 0 },
    { shipType: "1", useFrequency: 0, useDuration: 0, useAmount: 0 },
    { shipType: "2", useFrequency: 0, useDuration: 0, useAmount: 0 },
    { shipType: "3", useFrequency: 0, useDuration: 0, useAmount: 0 },
    { shipType: "4", useFrequency: 0, useDuration: 0, useAmount: 0 },
    { shipType: "5", useFrequency: 0, useDuration: 0, useAmount: 0 },
    { shipType: "6", useFrequency: 0, useDuration: 0, useAmount: 0 },
    { shipType: "7", useFrequency: 0, useDuration: 0, useAmount: 0 },
    { shipType: "8", useFrequency: 0, useDuration: 0, useAmount: 0 },
    { shipType: "9", useFrequency: 0, useDuration: 0, useAmount: 0 },
  ]
{
  "code":"0",
  "data":{
      "detailedList":[],
      "list":[
            { shipType: "3", useFrequency: 9, useDuration: 34, useAmount: 6 },
            { shipType: "5", useFrequency: 8, useDuration: 0, useAmount: 12 },
      ],
      "logInfo":[],
      "msg":"成功"}

我写了几个方法都不成功

// 方法一
let tableLists = tableList.map(item => item.shipType === res.data.list.shipType ? res.data.list : item)
        console.log(tableLists)
// 输出结果和数组1完全一样
// 方法二
        for(let i=0;i<tableList.length;i++){
          if(tableList[i].shipType === list1.shipType){
            tableList[i] = list1
          }
        }
// 输出结果和数组1完全一样

要怎么写?或者我写的方法有什么不对的地方?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

3条回答 默认 最新

相关推荐 更多相似问题