You could do this with two
reduce methods one to build vehicles array and other one to group in each object by provided array of keys.(您可以使用two
reduce方法来实现此目的,一种是构建车辆数组,另一种是通过提供的键数组将每个对象分组。)
const data = {"vehicles":[{"name":"Team1","cars":[{"multiple":0.5,"category":"cars"},{"multiple":0.5,"category":"cars"}],"bike":[{"multiple":0.5,"category":"bike"}],"scooter":[{"multiple":0.5,"category":"scooter"}]},{"name":"Team2","cars":[{"multiple":0.5,"category":"cars"},{"multiple":0.5,"category":"cars"}],"bike":[{"multiple":0.5,"category":"bike"}],"scooter":[{"multiple":0.5,"category":"scooter"}]}]}; function groupBy(data, keys) { return data.vehicles.reduce((r, {name,...rest}) => { const obj = Object.entries(rest).reduce((a, [k, v]) => { if (keys.includes(k)) { const key = keys.join('_'); if (!a[key]) a[key] = [...v]; else a[key].push(...v); } else a[k] = [...v] return a }, {name}) r.vehicles.push(obj) return r; }, { vehicles: [] }) } console.log(groupBy(data, ['bike', 'scooter'])) console.log(groupBy(data, ['bike', 'cars']))
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…