js 数组数据处理和整合

`

(2) [{…}, {…}]
    0:{article\_id:35,cat\_id:16,title:"麻黄"...}
    1:{article\_id:37,cat\_id:17,title:"tp5小程序", …}
    length:2
(2) [{…}, {…}]
    0:{cat\_id:16,cat\_name:"辛温解表药",cat\_type:0, …}
    1:{cat\_id:17,cat\_name:"测试", …}
length:2

`
拿到后台两个数组、需要组装成二维数组、后台返回不了二维数组。
期望得到这样的二维数组、怎么根据cat_id去判断,麻烦大佬们帮忙看看.
`

(2) [{…}, {…}]
0:{cat\_id:16,cat\_name:"辛温解表药",
    list:[article\_id:35,cat\_id:16,title:"麻黄"]
}
1:{cat\_id:17,cat\_name:"测试",
    list:[article\_id:37,cat\_id:17,title:"tp5小程序"]
}
length:2

`

阅读 3.4k
4 个回答

谢邀。

坦白说从给的数据里没有看出下面的 list 是怎么来的,可能逻辑在那些省略的 ... 里面吧。
不过题主你自己明白合并逻辑就好。

不建议直接要代码的方式。

给一个思路,遍历其中一个数组,以 cat_id 为 key 创建 map,再遍历另外一个数组根据你的合并逻辑做合并即可。
如果最终需要的是数组,把 map 再转成数组即可。
时间复杂度 O(n)。

这个还是比较基础的,复习下array自带的函数,array 文档

let arr1 = [
  {
    key1: 123,
    key2: 123
  }
];

const arr2 = [
  {
    key3: 123,
    key4: 123
  }
];

arr1 = arr1.map((item, index) => ({
  ...item,
  list: arr2.find(value => value.key3 === item.key1)
}));
let arr = [
  { article_id: 35, cat_id: 16, title: '麻黄' },
  { article_id: 37, cat_id: 17, title: 'tp5小程序' }
]

let arr2 = [
  { cat_id: 16, cat_name: '辛温解表药', cat_type: 0 },
  { cat_id: 17, cat_name: '测试' }
]

function formateData(parent, son) {
  if (!Array.isArray(parent) || !Array.isArray(son)) throw new Error('参数接受两个数组')
  return son.reduce((temp, item) => {
    let index = temp.findIndex(p => p.cat_id === item.cat_id)
    if (temp[index].list) {
      temp[index].list.push({ ...item })
    } else {
      temp[index].list = [{ ...item }]
    }
    return temp
  }, JSON.parse(JSON.stringify(parent)))
}

console.dir(formateData(arr2, arr))
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题