猿问

如何使用 lodash .map() 在结果中保留键名?

log(_.map(businessOpenSlots, weekday => {

        return _.spread(_.union)(_.map(weekday, slot => {

           return this.getTimeStops(slot.open, slot.close);

        }))

    } ))

这是上面的代码正在下面打印。但是,我想将键设为工作日,而不是 0..4。


不确定如何最好地实现这一点。

数据businessOpenSlots如下


{

   "friday":[

      {

         "open":"0900",

         "close":"1700"

      }

   ]"monday":[

      {

         "open":"0800",

         "close":"1530"

      },

      {

         "open":"1730",

         "close":"1930"

      }

   ]"thursday":[

      {

         "open":"0900",

         "close":"1700"

      }

   ]"tuesday":[

      {

         "open":"24hrs",

         "close":"24hrs"

      }

   ]"wednesday":[

      {

         "open":"0900",

         "close":"1700"

      }

   ]

}


哈士奇WWW
浏览 112回答 2
2回答

慕少森

您也可以使用 vanilla JS 相对简单地完成此操作。这是一个版本:const hoursToTimeStops = businessOpenSlots =>  Object .fromEntries (    Object .entries (businessOpenSlots) .map (([d, h]) => [d, h .flatMap (vm .getTimeStops)])  )const businessOpenSlots = {monday: [{open: "0800", close: "1530"}, {open: "1730", close: "1930"}], tuesday: [{open: "24hrs", close: "24hrs"}], wednesday: [{open: "0900", close: "1700"}], thursday: [{open: "0900", close: "1700"}], friday: [{open: "0900", close: "1700"}]}console .log (hoursToTimeStops (businessOpenSlots)).as-console-wrapper {max-height: 100% !important; top: 0}<script> // Dummy implementation for `vm`.const every15mins = (sh, sm, eh, em) => sh * 60 + sm > eh * 60 + em ? [] : [`${String(sh).padStart(2, '0')}:${String(sm).padStart(2, '0')}`, ...every15mins(sh + (sm >= 45 ? 1 : 0), (sm + 15) % 60, eh, em)]const vm = {getTimeStops:  ({open, close}) => open === '24hrs' ? ["00:00"] : every15mins(Number(open.slice(0, 2)), Number(open.slice(2, 4)), Number(close.slice(0, 2)), Number(close.slice(2, 4)))}</script>lodash (或 Ramda 的)很好地封装了调用entries、mapping 结果、然后调用的过程,但其余部分似乎比您的 lodash 版本更简单。fromEntriesmapValuesmap但是,我相信您应该能够大大简化该版本。我对 Ramda 更熟悉(免责声明:我是它的作者之一),而且我知道在 Ramda 中,我们可以简单地写:const hoursToTimeStops = map (chain (vm.getTimeStops))我猜你可以用 lodash 代替mapValues和mapitsflatMap代替chain. (除非你使用 Lodash FP,否则它可能不会那么优雅,但也不会差那么远。)

aluckdog

自己找到解决方案并在此处发布以供社区使用。我只需要使用_.mapValues()Lodash。let availableSlots = _.mapValues(businessOpenSlots, function(slots, weekday) {&nbsp; &nbsp; &nbsp; &nbsp;return _.spread(_.union)(_.map(slots, slot => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return vm.getTimeStops(slot.open, slot.close);&nbsp; &nbsp; &nbsp; &nbsp;}))&nbsp; &nbsp; });log(availableSlots)它返回以下内容,正如我想要的那样。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答