Reputation: 55273
I have objects like this inside an array:
{
"objectId": "566013c860b202595a4b6fd9",
"createdAt": "2015-12-03T10:04:56.367Z",
},
I'm using Underscore's _.where
to find them based on createAt
:
var adminsThisMonth = _.where(admins, {createdAt: adminCreatedAt})
Is there any way to find an object only based on one section of createdAt
, say, the two digits between the hyphens? (12
in this case).
Upvotes: 0
Views: 103
Reputation: 8021
Use _.filter()
to which you can pass a predicate function to filter the object with any logic you want.
_.filter(admins, function (obj) {
return checkConditon(obj.created);
});
Upvotes: 2
Reputation: 992
Use plain JS like this:
var admins =[
{
"objectId": "566013c860b202595a4b6fd9",
"createdAt": "2015-12-03T10:04:56.367Z",
}
]
var checkCreatedAt = (admins.map(function(obj){ return obj.createdAt; }).toString().indexOf("-12-") != -1) ? true : false;
...then you can use checkCreatedAt
as you wish.
Upvotes: 1
Reputation: 3268
Use the Method find, it is similar to where but takes an function as a second parameter. Then use the suggested code from @Tushar inside that function.
_.find(admins, function(admin) {
return admin.createdAt.indexOf('-12-') > -1;
});
Upvotes: 1
Reputation: 36703
var obj = {
"objectId": "566013c860b202595a4b6fd9",
"createdAt": "2015-12-03T10:04:56.367Z",
};
if(obj.hasOwnProperty("createdAt") && obj.createdAt.indexOf("-12-")>-1){
...
}
Checking first whether it has the key or not and if it has that key then check for the index of -12-
Upvotes: 1