javascript - Accessing single field from object in array -
i'm using meteor mongodb , can't seem figure out how access single field objects in object array.
my documents:
{ "_id" : "p6c4cstb3chwajqpg", "createdat" : isodate("2016-05-11t11:30:11.820z"), "username" : "admin", "contacts" : [ { "when" : isodate("2016-05-11t11:30:32.350z"), "who" : "4ybufbe9pbyjbkasy" }, { "when" : isodate("2016-05-25t11:52:49.745z"), "who" : "z792keeybxyzyeakp" }, { "when" : isodate("2016-05-26t13:47:43.439z"), "who" : "4ybufbe9pbyjbkasy" }, { "when" : isodate("2016-05-26t13:48:22.828z"), "who" : "4ybufbe9pbyjbkasy" } ] }
i want check if userid
in of objects, in who
fields.
my server-side code:
var me = meteor.userid(); var findme = meteor.users.findone(me); if (_.include(findme.contacts, {who: 4ybufbe9pbyjbkasy})){ console.log("found in array"); }else{ console.log("not found in array"); } }
i have tried several different ways, came nothing.
when console.log(findme.contacts);
, returns whole array should. when try console.log(findme.contacts.who);
, returns undefined
.
just need direction on how access field of object array. thanks!
looping through array see whether contains value done array.prototype.some:
var data = { "_id" : "p6c4cstb3chwajqpg", "createdat" : "2016-05-11t11:30:11.820z", "username" : "admin", "contacts" : [ { "when" : "2016-05-11t11:30:32.350z", "who" : "4ybufbe9pbyjbkasy" }, { "when" : "2016-05-25t11:52:49.745z", "who" : "z792keeybxyzyeakp" }, { "when" : "2016-05-26t13:47:43.439z", "who" : "4ybufbe9pbyjbkasy" }, { "when" : "2016-05-26t13:48:22.828z", "who" : "4ybufbe9pbyjbkasy" } ] }; var hascontact = function(contacts, id){ return contacts.some(function(contact){ return contact.who === id; }); }; console.log(hascontact(data.contacts,'4ybufbe9pbyjbkasy')); console.log(hascontact(data.contacts,'z792keeybxyzyeakp')); console.log(hascontact(data.contacts,'asdfasdfasdfasdfa'));
Comments
Post a Comment