发射到特定的套接字(如耳语),其中包含特定的socket.name
我有我的sockets这样存储在一个对象“人”。 但是现在我想在people.name中提取符合条件的对象,例如[“4323”,“9”,“43535”],例如9.意思是在这种情况下提取“OGyF_FMFbsr0ldcbAAAK”套接字。
通过导航[“4323”,“9”,“43535”]来查找它们是否在人员中,然后向包含people.name === 9的套接字发送通知。 可能不止一个套接字。
所以。
对于每个“参加”
["4323","9","43535"]
在人们”
{ "ZA-CJOc1PtiwDVxkAAAD": {"name":"4","owns":"2-0-62","inroom":"2-0-62","device":"desktop"}, "wKg2rcFSHgcl4m3WAAAG": {"name":"3","owns":"2-0-110","inroom":"2-0-110","device":"desktop"}, "OGyF_FMFbsr0ldcbAAAK": {"name":"9","owns":null,"inroom":null,"device":"desktop"} }
然后发射
io.sockets.socket(id).emit("notification", result);
问题:
如何使正确的代码select套接字来发送通知?
那么如何发出每个通知呢?
提前致谢
如果我明白你的要求是正确的,那么一种方法是迭代你的people
对象的键,比较他们每个people
的name
属性与attending
arrays中的元素,并将任何匹配的键推入found
新的arrays,获取名单在您的attending
名单中find的人员列表。
然后,您可以迭代found
数组,以便将消息发送到与您的search条件匹配的people
对象中的客户端。
var attending = ['4323', '9', '43535'], found = []; var people = { 'ZA-CJOc1PtiwDVxkAAAD': { 'name': '4', 'owns': '2-0-62', 'inroom': '2-0-62', 'device': 'desktop' }, 'wKg2rcFSHgcl4m3WAAAG': { 'name': '3', 'owns': '2-0-110', 'inroom': '2-0-110', 'device': 'desktop' }, 'OGyF_FMFbsr0ldcbAAAK': { 'name': '9', 'owns': null, 'inroom': null, 'device': 'desktop' } }; for (var person in people) { for (var i = 0, numAttending = attending.length; i < numAttending; i++) { if (people[person].name === attending[i]) { found.push(person); } } } for (var i = 0, numFound = found.length; i < numFound; i++) { io.sockets.socket(found[i]).emit('notification', result); };
编辑
如果你想把整个物体推到你found
数组上,你可以这样做。 由于整个对象,而不是只有客户端ID被存储在数组中,下面的发射循环需要稍微调整,以保持工作。
for (var person in people) { for (var i = 0, numAttending = attending.length; i < numAttending; i++) { if (people[person].name === attending[i]) { found.push(people[person]); //this would give something like this, without the socket id //[{"name":"3","owns":null,"inroom":null,"device":"desktop"}] } } } for (var person in found) { io.sockets.socket(person).emit('notification', result); };