繁体   English   中英

如何使用lodash在数组中查找具有值的对象

[英]How to find object with value in array using lodash

给出以下 JS 数组:

vm.todayShifts = [];
vm.todayShifts['am'] = 
    {
      station: "1",
      slots: {
        position: "AO", 
        name: "Person One"
      },
      slots: {
        position: "FF", 
        name: "Person Two"
      },
      slots: {
        position: "PFF", 
        name: "Person Three"
      },
    },
    {
      station: "2",
      slots: {
        position: "AO", 
        name: "Person Four"
      },
      slots: {
        position: "FF", 
        name: "Person Fve"
      },
      slots: {
        position: "PFF", 
        name: "Person Six"
      },
    },
  ],
todayShifts['pm'] = 
    {
      station: "1",
      slots: {
        position: "AO", 
        name: "Person Seven"
      },
      {
        position: "FF", 
        name: "Person Eight"
      },
      {
        position: "PFF", 
        name: "Person Nine"
      },
    },
    {
      station: "2",
      slots: {
        position: "AO", 
        name: "Person Ten"
      },
      {
        position: "FF", 
        name: "Person Eleven"
      },
      {
        position: "PFF", 
        name: "Person Twelve"
      },
    },
  ]

在循环中的某一点,我有 station.id 和 dayPart(am 或 pm)值,我需要查看 todayShift 数组是否包含在适当的 dayPart 中并具有 station.id 值的对象,然后返回该对象(如果存在)。 我用 lodash 试过这个:

      if (typeof vm.todayShifts[dayPart] != 'undefined') {
        var shift = _.find(vm.todayShifts[dayPart], {'station': station.id});
      }

但即使存在符合条件的数据(例如 dayPart="am" 和 station = 1),也不会返回任何内容。

这已经在一个循环中(在一个带有 Angular Bootstrap 日历的自定义单元格模板单元格修改器中),所以如果我不需要的话,我不想每次都遍历 todayShifts,因为这个控制器将被调用 ~30每页次数。

我很亲近吗? 或者是否有更简单的方法来检查和获取该对象?

谢谢。

改用函数

var shift = _.find(vm.todayShifts[dayPart], function(shift){ return shift.station ==  station.id });

查看控制台查看结果。

 vm = Object; vm.todayShifts = []; vm.todayShifts['am'] = [ { station: "1", slots: [{ position: "AO", name: "Person One" }, { position: "FF", name: "Person Two" }, { position: "PFF", name: "Person Three" }] }, { station: "2", slots: [{ position: "AO", name: "Person Four" }, { position: "FF", name: "Person Fve" }, { position: "PFF", name: "Person Six" }] }, ], vm.todayShifts['pm'] = [ { station: "1", slots: [{ position: "AO", name: "Person Seven" }, { position: "FF", name: "Person Eight" }, { position: "PFF", name: "Person Nine" }] }, { station: "2", slots: [{ position: "AO", name: "Person Ten" }, { position: "FF", name: "Person Eleven" }, { position: "PFF", name: "Person Twelve" }] } ] function getShift(dayPart, stationId){ if (typeof vm.todayShifts[dayPart] != 'undefined') { var shift = _.filter(vm.todayShifts[dayPart], {'station': stationId}); return shift; } } var ob = getShift("pm", "2"); console.log(ob);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

暂无
暂无

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

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