[英]Iterate through an object and find value by key in javascript
I have an array of objects, like this 我有一个对象数组,像这样
I would like to iterate through an array and find users by specific roomCode 我想遍历数组并通过特定的roomCode查找用户
I tried this: 我尝试了这个:
for(let i=0; i <data.liveRooms.length; i++) {
if(data.liveRooms[i].roomCode === code) {
this.usersLive = data.liveRooms[i].users;
}
}
And also this: 还有这个:
for(let i=0; i <data.liveRooms.length; i++) {
this.liveDataDictionary[data.liveRooms[i].roomCode] =
data.liveRooms[i].users;
}
this.usersLive = this.liveDataDictionary[code];
But nothing works and I don't know why...could you please help me? 但是什么都没用,我也不知道为什么……你能帮我吗?
According to the screenshot you posted, data.liveRooms[i]
is a string, not an object. 根据您发布的屏幕截图,
data.liveRooms[i]
是字符串,而不是对象。 You could try this inside your for
loop: 您可以在
for
循环中尝试以下操作:
for(let i=0; i <data.liveRooms.length; i++) {
let liveRoom = JSON.parse(data.liveRooms[i]);
if(liveRoom.roomCode === code) {
....
}
}
The JSON.parse()
method is a built-in that will convert that string that looks like an object to an actual object. JSON.parse()
方法是内置的,它将把看起来像对象的字符串转换为实际对象。 At that point you will be able to get to the dot properties of the object, like .roomCode
. 届时,您将可以获取对象的点属性,例如
.roomCode
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.