猿问

两数组通过id关联,怎样通过js把他们合并成一个数组?

例如


 a = [{id:1,age:10},{id:2,age:20},{id:3,age:30}] 

 b = [{id:3,sex:'男'},{id:1,sex:'男'},{id:2,sex:'女'}]

合并后


c = [{id:1,age:10,sex:'男'},{id:2,age:20,sex:'女'},{id:3,age:30,sex:'男'}]


翻阅古今
浏览 1545回答 2
2回答

qq_笑_17

<script>&nbsp; const a = [{id:1,age:10},{id:2,age:20},{id:3,age:30}];&nbsp; const b = [{id:3,sex:'男'},{id:1,sex:'男'},{id:2,sex:'女'}];&nbsp; let c = [];&nbsp; for(let u of a) {&nbsp; &nbsp; const temp = b.filter(i => i.id === u.id)[0];&nbsp; &nbsp; c.push({...u, ...temp});&nbsp; }&nbsp; console.log(c);</script>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答