简体   繁体   English

遍历对象并通过javascript中的键查找值

[英]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

JSON.parse() at MDN . MDN的JSON.parse()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何遍历深层嵌套对象并找到特定键的值? - How to iterate through deep nested object and find value of a particular key? 如何在javascript中迭代对象作为键值对 - How to iterate through object as key value pair in javascript 如何使用键遍历 object 并获取值 - How to iterate through an object with key and get the value 遍历javascript对象并动态添加对象属性(JS对象中的键值对) - Iterate through javascript object and add object properties dynamically (key-value pair in JS object) JavaScript-遍历对象以查找特定的键值 - JavaScript - Loop through Object to find Specific Key Value JavaScript - 如何遍历对象数组以创建一个新对象,其键是原始对象的初始键/值对的值 - JavaScript — how to iterate through an array of objects to create a new object whose key is the value of the original object's initial key/value pair JavaScript | 遍历JSON对象并获取特定键的所有值 - JavaScript | Iterate through JSON Object and get all the values for a specific key 遍历数组并打印html foreach键/值的Javascript / jQuery - iterate through array and print html foreach key/value Javascript / jQuery Mongodb mapreduce迭代对象的键值对 - Mongodb mapreduce iterate through object's key value pairs 如何遍历javascript对象以找到多个相似的键 - How to iterate through javascript object to find multiple similar keys
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM