🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
>[danger] 合并对象_排序 ---- > 思路1: 双层循环, 挨个比, 最后排序 --- > 思路2: 合并数组, 向map添加, id为key, 合并对象, 最后排序 --- 题意: 现有如下数组, 根据ID值相同合并对象, 以age排序, 打印数组结果 ~~~ let arr = [ { "id": 1, "text": "大嫂" }, { "id": 3, "text": "三嫂" }, { "id": 2, "text": "二嫂" } ]; let brr = [ { "id": 1, "age": 30 }, { "id": 2, "age": 17 }, { "id": 3, "age": 23 } ]; ~~~ 1. 方式1: 循环a数组, 与b数组每个判断id是否相等 ~~~ let resultArr = []; arr.map(oneObj=>{ brr.map(twoObj=>{ if (oneObj['id'] === twoObj['id']){ resultArr.push(Object.assign({}, oneObj, twoObj)); } }) }); console.log(resultArr.sort((a, b)=>a['age'] - b['age'])); ~~~ 2. 方式2: 循环a数组, 去b数组find到id相等的元素 (实际上还是双层循环) ~~~ let resultArr = []; arr.map(oneObj => { let target = brr.find(twoObj => oneObj['id'] === twoObj['id']); resultArr.push(Object.assign({}, oneObj, target)); }); console.log(resultArr.sort((a, b)=>a['age'] - b['age'])); ~~~ 3. 方式3: 循环所有元素, id为key, 合并对象为value (这种最快) ~~~ let map = new Map(); arr.concat(brr).forEach(obj => { map.set(obj.id, Object.assign(map.get(obj.id) || {}, obj)); }); console.log(Array.from(map.values()).sort((a, b)=>a['age'] - b['age'])); ~~~