简体   繁体   English

如何从数组中嵌套具有重复值的对象

[英]How can I nest objects from an array that have repeating values

I've got an array of objects for bus arrivals. 我有很多东西可以到达公共汽车。 The array has objects that have repeating properties but different times. 该数组的对象具有重复属性,但时间不同。 I would like to nest the buses that come later into the bus that comes first. 我想将后来出现的总线嵌套到首先出现的总线中。 Also the array is ordered by arrival time. 阵列也按到达时间排序。

[ 
   { Arrival, busId: "123", minToStop: 16, timeToStop: 957 },
   { Arrival, busId: "123", minToStop: 23, timeToStop: 1390 } 
]

Is there any nice and easy way to do it in javascript? 在JavaScript中,有没有任何简便的方法?

This is what I want to get 这就是我想要的

[ 
   { Arrival, busId: "123", minToStop: 16, timeToStop: 957, laterBuses: 
      [
         { Arrival, busId: "123", minToStop: 23, timeToStop: 1390 },
         { Arrival, busId: "123", minToStop: 30, timeToStop: 1820 }
      ]
   }
]

You can reduce the array to one value (a Map ) and then spread the values of that map as new array: 您可以将数组缩小为一个值(一个Map ),然后将该地图的值作为新数组散布

 const busses = [ { busId: '234', minToStop: 40, timeToStop: 1390 }, { busId: '123', minToStop: 16, timeToStop: 957 }, { busId: '123', minToStop: 23, timeToStop: 1490 }, { busId: '234', minToStop: 17, timeToStop: 957 }, { busId: '123', minToStop: 40, timeToStop: 1390 }, { busId: '123', minToStop: 30, timeToStop: 1390 }, { busId: '234', minToStop: 1, timeToStop: 1490 }, ]; console.log([ ...busses .sort((a, b) => a.minToStop - b.minToStop) .reduce((result, bus) => { const parentBus = result.get(bus.busId); const current = parentBus || { ...bus, laterBusses: [], }; if (!!parentBus) { //only add to laterbusses if it's not the first bus found current.laterBusses.push(bus); } return result.set(current.busId, current); }, new Map()) .values(), ]); 

This solution will first sort the buses by minToStop and then by busId . 该解决方案将首先按minToStop排序总线,然后按busId It then iterates through the buses array and conditionally puts the bus at the top level of a final array or nested as you requested. 然后,它通过遍历buses阵列和有条件地把公交车在顶层final数组或嵌套按照您的要求。

 const buses = [ { busId: "234", minToStop: 40, timeToStop: 1390 }, { busId: "123", minToStop: 16, timeToStop: 957 }, { busId: "123", minToStop: 23, timeToStop: 1490 }, { busId: "234", minToStop: 17, timeToStop: 957 }, { busId: "123", minToStop: 30, timeToStop: 1390 }, { busId: "234", minToStop: 1, timeToStop: 1490 } ]; buses.sort((a,b) => a.minToStop - b.minToStop); buses.sort((a,b) => a.busId > b.busId); let formatted = []; buses.forEach(bus => { if ( formatted.length > 0 && formatted[formatted.length - 1].busId === bus.busId ) { formatted[formatted.length - 1].laterBuses.push(bus); } else { bus.laterBuses = []; formatted.push(bus); } }); console.log(formatted); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM