wonder95 wonder95 - 4 months ago 15
Javascript Question

How to find object with value in array using lodash

Give the following JS array:

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"
},
},
]


at one point in a loop, I have the station.id and dayPart (am or pm) values, and I need to see if the todayShift array contains an object that is in the appropriate dayPart and has the station.id value, and return that object if it exists. I've tried this with lodash:

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


but nothing is returned even when there is data that matches the criteria (e.g. dayPart="am" and station = 1).

This is already in a loop (inside a cell modifier for a custom cell template with Angular Bootstrap calendar), so I don't want to loop through todayShifts every time if I don't have to, since this controller will get called ~30 times per page.

Am I close? Or is there an easier way to check for and get that object?

Thanks.

Answer

use a function instead

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