请教一个数组的问题
有两个数组,合并成一个数组
数组一:[{id:"150",name:"李三"},{id:"151",name:"李三 1"},{id:"152",name:"李三 2"},{id:"153",name:"李三 3"}]
数组二:[{"sname":"一级","otor":["李三 1","150"]},{"sname":"一级 2","otor":["李三 2"]},,{"sname":"一级 3","otor":["153"]},]
最后合并成数组:[{"sname":"一级","otor":[{id:"151",name:"李三 1"},{id:"150",name:"李三"}]},{"sname":"一级 2","otor":[{id:"152",name:"李三 2"}]},,{"sname":"一级 3","otor":[{id:"153",name:"李三 3"}]},]
1
zantop 2019-06-26 11:32:36 +08:00
const arr1 = [
{ id: '150', name: '李三' }, { id: '151', name: '李三 1' }, { id: '152', name: '李三 2' }, { id: '153', name: '李三 3' } ]; const arr2 = [ { sname: '一级', otor: ['李三 1', '150'] }, { sname: '一级 2', otor: ['李三 2'] }, { sname: '一级 3', otor: ['153'] } ]; arr2.map((item, index) => { const temArr = []; item.otor.map((ele, idx) => { const ar = arr1.filter((a, b) => ele === a.id || ele === a.name); if (ar.length > 0) { temArr.push(ar[0]); } }); item.otor = temArr; }); console.log(arr2) |
2
Colorful OP @zantop 请教下
假如说再变化一下方式应该是怎么样修改?在第二个数组里面多加了一个新的,在第一个数组里面是没有的。 数组一:[{id:"150",name:"李三"},{id:"151",name:"李三 1"},{id:"152",name:"李三 2"},{id:"153",name:"李三 3"}] 数组二:[{"sname":"一级","otor":["李三 1","150"]},{"sname":"一级 2","otor":["李三 2"]},{"sname":"一级 3","otor":["153"]},{"sname":"一级 4","otor":[{id:"1531",name:"李三 31"}]},] 最后合并成数组:[{"sname":"一级","otor":[{id:"151",name:"李三 1"},{id:"150",name:"李三"}]},{"sname":"一级 2","otor":[{id:"152",name:"李三 2"}]},{"sname":"一级 3","otor":[{id:"153",name:"李三 3"}]},{"sname":"一级 4","otor":[{id:"1531",name:"李三 31"}] |
3
sunriz 2019-06-26 11:47:27 +08:00
建议把 json 排好版再发,有相关网站。看得难受
|
5
source 2019-06-27 09:18:12 +08:00
|
6
source 2019-06-27 09:19:59 +08:00
手抖,v.otor 前面多了一对中括号
|