Exploring an object to retrieve values based on keys using javascript

Currently, I have an array of objects set up like this:

https://i.sstatic.net/l6d3z.png

My goal is to loop through the array and extract users based on a specific roomCode

So, I've attempted two different approaches:

      for(let i=0; i <data.liveRooms.length; i++) {
        if(data.liveRooms[i].roomCode === code) {
          this.usersLive = data.liveRooms[i].users;
        }
      }

And then I tried another method as follows:

for(let i=0; i <data.liveRooms.length; i++) {
    this.liveDataDictionary[data.liveRooms[i].roomCode] = 
      data.liveRooms[i].users;
 }
  this.usersLive = this.liveDataDictionary[code];

Unfortunately, none of these techniques seem to be doing what I want them to do, but I'm not sure why. Could someone please help me figure this out?

Answer №1

Based on the screenshot provided, it appears that data.liveRooms[i] is a string rather than an object. To address this, consider implementing the following snippet within your for loop:

for(let i=0; i <data.liveRooms.length; i++) {
  let liveRoom = JSON.parse(data.liveRooms[i]);
    if(liveRoom.roomCode === code) {
      ....
    }
}

By utilizing the JSON.parse() method, you can effectively convert the string resembling an object into an actual object. This will enable you to access the properties of the object using dot notation, such as .roomCode.

For more information on JSON.parse(), refer to the documentation at MDN.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to use a Handlebars file on multiple routes?

I have been working on extracting articles from a news website by scraping them successfully. The data is being displayed properly on the front-end console log, but I am facing an issue with rendering it onto the page using a button - it only appears when ...

Adjusting the brightness of colors using JavaScript

I am looking for a way to return different color tones for a specific color using JavaScript. For example, if I have the color code #4a4a4a, I want to be able to return #494949 and #666464. If there is a package or method that can achieve this, please sugg ...

Retrieve the HTML contents of a cell that contains a checkbox with the value of "jquery"

Here is an example of a table row: <tr> <td><input type='checkbox' name='post[]' value="1"></td> <td>08-Apr-2014</td> <td>injj team</td> <td>merchant.testyy.com</ ...

Is there a way for me to extract text from a leaflet popup in order to generate the complete URL for an AJAX request?

When text within a popup is clicked, I want to trigger an ajax call. The content in the leaflet popup has been set previously by another ajax call. Below is the JavaScript code for both ajax calls: $("#button").click(function() { var name = document. ...

Incorporating a specific time to a JavaScript date object

In my Angular application, I am facing an issue with adding a time to a date. The appointmentDate from the date picker returns a JavaScript date while the appointmentTime is selected from a dropdown with options like "8:00", "8:30", "9:00", etc. I'm ...

Navigating the use of PHP variables in JavaScript

Whenever I select an option from the menu, a Javascript function changes the input value based on a PHP variable. Below is an example of how I assign values from 1 to n to each option: $i = 0; foreach($videos as $val) { echo '<option value=&ap ...

"Deleting a specific row from a SQL Server using Node.js: Step-by-Step Guide

Currently, my setup involves using nodeJs as the backend language and sql server as the database. While I have managed to delete whole table rows from the database successfully, I am facing a challenge when it comes to deleting a specific row. Here is the ...

Troubleshooting the Vue.js component rendering issue

I am trying to display only one object from the data on firebase using [objectNumber]. I want to show {{ligler[1].name}} in the template, but it is causing errors: Error when rendering component Uncaught TypeError: Cannot read property 'name' o ...

How to adjust cell alignment in Handsontable

Handsontable showcases cell alignment options in the align cell demo: Horizontal Left Center Right Justify Vertical Top Middle Bottom Displayed below is a screenshot: To retrieve data, utilize the following code snippet: $('#table-wrapper&ap ...

Nested loops in JavaScript can be combined with promises to efficiently handle

I am facing a challenge in looping through an array that contains another array as one of the parameters. My goal is to iterate through this nested array according to specific requirements, and then execute a function once the parent loop is finished. Can ...

Is there a way to trigger an AJAX request right before I leave the page or unload it?

When the window is about to be unloaded, an AJAX request is sent to a specific URL including the recent tracking ID and the time spent on the page in seconds. However, the behavior I am experiencing is an alert displaying [object Object]. ...

What is the best way to retrieve the value from a textarea and verify if it is blank or not?

I have successfully incorporated a textarea using simpleMde, but I am facing difficulty in retrieving the value and checking whether it is empty or not. var message = document.getElementById("simpleMde").value; console.log(message); <textarea class=" ...

PapaParse is not properly recognizing the date format

Having trouble creating a chart using JSON data from papaparse, resulting in the following error: c3.js:2100 Failed to parse x '10-18-2018' to Date object I've tried adjusting the date format in the CSV file but haven't had any luck. I ...

Guide to parsing unprocessed JSON into a specified format including a Date field

I need help figuring out how to import a raw JSON data file and automatically convert my date string to a date object within my type. In my type definition: export type Client = { id: number; first_name: string; last_name: string; dob: Dat ...

Preventing Context Menu from Appearing on Long Click in HTML5 Games

I'm attempting to utilize a similar technique as demonstrated in this stackoverflow post: How to disable the 'save image as' popup for smartphones for <input> However, I am encountering an issue where my button is not displaying at ...

In React, components will consistently render the initial code

I have a chat application that requires authentication and uses cookies. Here's what I've been attempting: class AppHeader extends React.Component { constructor(props) { super(props) } render() { if (cookies.get(' ...

The interplay between javascript and PL/SQL tasks in a dynamic scenario

I'm attempting to run multiple pl/sql blocks within a Dynamic Action, providing real-time feedback to the user through a modal dialog displaying the current status. Here is an example of what I am trying to achieve: Processing Step 1... /*Run pl/s ...

"Utilizing the power of ng-click to target specific child

I am facing an issue with my owl carousel where events are not firing on cloned items. In search of a solution, I came across a suggestion from Stack Overflow to move the event handler from the direct target to its parent element: Original code snippet: ...

How to reference an image located in one folder from a page in a different folder using React

Imagine there is Folder A containing an image called 'image.jpg' and Folder B with an HTML page that needs to access the image in Folder A in order to display it. The following code successfully accomplishes this task: <img src={require(&apo ...

Confirm that the string is in the correct JavaScript Date format

I'm encountering an issue with validating the specified string obtained from the new Date() Object. "2020-10-06T14:23:43.964Z". I anticipate receiving either this particular input format or a new Date(). My aim is to create something that ca ...