extract data from a JavaScript object

Currently facing an issue extracting a String name from the JSON object's name. It is necessary to parse this type of JSON response obtained from the server.

var response = {
  hopaopGmailsjIpW: {
    GmailsjIpW_totalEmails_count: 133,
    GmailsjIpW_state: 1
  },
  hopaopGmail4y4yu: {
    Gmail4y4yu_totalEmails_count: 156,
    Gmail4y4yu_state: 1
  }
}

This is not an Array, but rather an object with nested objects. The goal is to extract the names of these inner objects and add extra values to each one.

The desired functionality should be something like this:

for(var i =0; i < response.length; i++){
  response[i].username = parseUsernameFromString(response[i]);
  response[i].service = parseServiceFromString(response[i]);
  response[i].id = parseIdString(response[i]);
}

(and also checking the state for each task)

Therefore, the question arises: What would be the most effective approach to achieve this?

UPDATE This is the current solution attempted:

for(var key in response){
    if(stringContains(response[key], "Gmail")) { response[key].service = "Gmail";}
        console.log("task name: "+ response[key].service);
}
function stringContains(originalString, searchString){
        if(originalString.indexOf(searchString) > -1){
            return true
        }
            else return false;
}

Answer №1

When navigating through Objects, it is essential to utilize the for ... in loop.

The issue at hand is: A necessary , is absent from your code. Take a look at the corrected functioning snippet below:

Snippet

var response_Parsed = {
  hopaopGmailsjIpW: {
    GmailsjIpW_totalEmails_count: 133,
    GmailsjIpW_state: 1,
    service: 'Gmail',
    username: 'hopaop',
    id: 'sjIpW'
  },
  hopaopGmail4y4yu: {
    Gmail4y4yu_totalEmails_count: 156,
    Gmail4y4yu_state: 1,
    service: 'Gmail',
    username: 'hopaop',
    id: '4y4yu'
  }
};
for (id in response_Parsed) {
  console.log("----");
  if (id.indexOf("Gmail") > -1) {
    console.log("We have Gmail: " + id);
    console.log("UniqueName:    " + id.replace("hopaopGmail", ""));
    console.log("Username:      " + response_Parsed[id].username);
    console.log("Email Count:   " + response_Parsed[id][id.replace("hopaop", "") + "_totalEmails_count"]);
  }
  else
    console.log("We don't have Gmail: " + id);
}

Furthermore, the preferred method for iterating through the keys of objects is by using Object.keys.

Answer №2

When handling a response that is in String format, the first step should be to parse the JSON-String into an Object. Many libraries like jQuery automatically handle this conversion for you:

var data = JSON.parse(responseString);

Once you have converted the string into an object, you can iterate through it using a loop:

for (var property in data) {
    console.log("property", property, "value", data[property]);
}

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

Extracting certain elements from a text: a beginner's guide

I am currently developing a task manager that includes a feature to generate a PDF file using jsPDF. I am facing the challenge of extracting specific attributes from a string in order to print them as text utilizing jsPDF. The provided string is: [{" ...

Leveraging Multiple Angular.js Controllers within a Shared DOM

As someone who is fairly new to Angular.js, I am currently working on integrating it into my Node.js application. While I have successfully created a RESTful API using Angular for a single controller, I am now looking to utilize two or more controllers wi ...

Get information from processed json list

I'm dealing with a code snippet where I need to extract each section of an array individually. Here is the code in question: $parsed = $parsed_json['forecast']['txt_forecast']['forecastday']; foreach($parsed as $key =& ...

The jQuery Validate Plugin only validates emails when the user moves away from the input field

Resolved: Upon inspecting my version of jquery-validate.js, I discovered that it was missing the onkeyup handler. Despite using version 1.12 Opre, which should have had this functionality according to its Github history from 2013, it seemed like there may ...

TypeOrm is struggling to identify the entities based on the directory path provided

Currently, I am utilizing TypeORM with NestJS and PostgreSql to load entities via the datasource options object. This object is passed in the useFactory async function within the TypeORM module as shown below: @Module({ imports: [TypeOrmModule.forRootAsy ...

Retrieve the JSON element from a Backbone model by its unique identifier

I'm diving into Backbone for the first time and I'm facing difficulties making it work smoothly with a JSON data file. Here's how my model looks: window.Test = Backbone.Model.extend({ defaults: { id: null, name: null, }, url: f ...

Enhancing functionality through the press of a button

I wrote a script that, upon button click, finds the closest location to your current position by searching through an array. It then locates the corresponding entry in another array and adds a number to that entry. However, I encountered a problem with app ...

Switching between API requests through a live feed

Hey there: import Rx from 'rxjs'; function mockApi(endpoint, time, response) { return new Rx.Observable(observer => { console.log(`${endpoint}: Request initiated.`) let active = true; const id = setTimeout(() => { cons ...

Utilizing prerender.io with lazy loading in Angular 2: A comprehensive guide

As Angular Universal is not expected to be included in the CLI for some time, I've had to resort to using prerender.io in order to ensure proper SEO functionality. However, my tests have shown that there are issues with lazy loaded modules causing SEO ...

Tracking the number of form submissions on a PHP website

I am looking to add a counter feature to my website where every time a form is submitted, the count increases for all visitors. The starting number will be 0 and each form submission will increment the count. While I can manage the count using JS/jQuery w ...

HTML not updating after a change in properties

My template is structured as a table where I update a column based on a button click that changes the props. Even though the props are updated, I do not see the template re-rendered. However, since I am also caching values for other rows in translatedMessa ...

Disable the ability to close the dialog box by clicking

this is my dialog <div *ngIf="visible" class="overlay" (click)="close()"> <div role="dialog" class="overlay-content"> <div class="modal-dialog" (click)="$event.stopPropagation()"> <!-- Modal content--> ...

Ways to display URL parameters on an HTML page without using PHP

I'm currently working on a website using HTML (without PHP) and I'm facing an issue with displaying URL parameters on an appointment confirmation page. The appointment details are being successfully passed through the URL parameters, but I'm ...

Interactive hover effect in JavaScript displays a larger version of other thumbnails when hovering over a dynamically loaded thumbnail image, instead of its own full-size image

I recently began teaching myself PHP and Dreamweaver with the help of a video tutorial on building data-driven websites using Dreamweaver. My goal is to create a dynamic table with 6 columns and 20 rows. column1 | column2 | column3 | colu ...

Issues with Angular toggle sorting functionality not functioning as expected

$scope.searchObject = { from: 0, hydrate: false, size: 12, sort: 'timestamp:desc' }; $scope.sort = function(a) { var ascend = a + ':' + 'asc'; var descend = a + ':' + 'desc'; if ($scope.searc ...

Troubleshooting problems encountered when duplicating an array in JavaScript

I am attempting to utilize properties and flatmap to modify an array without altering the original data. I have implemented this method in two different instances within a single dispatch call in Vue.js when transferring data from parent to children comp ...

Issue with Rails manifest assets being undefined or not recognized as an object when making an AJAX request in Internet Explorer 8

I am attempting to retrieve the file names of certain files using ajax from the Manifest.json file. Our file names are digested, which is why I need to access them this way in order to use ajax later on. Here is the code snippet I am currently using: $.aj ...

Filter the JSON using jq to select one attribute that matches another

Here's the JSON input: { "data": { "zone": [ { "record": [ { "Line": 1, "raw": "; cPanel first:11.25.0-CURRENT_46156 (update_time):1708598274 Cpanel::ZoneFile::VERSION:1.3 hostname:server2.somethin ...

Setting up the ajax header and implementing a redirect

I have a simple node authentication app. My goal is to send a token in the header when redirecting to a URL. For example, when a user clicks on their profile, they should be redirected with a token so they can access that page. I've tried implementin ...

Get a list of all languages supported by browsers using JavaScript

Within my HTML user interface, I have a dropdown that needs to display a list of all installed browser languages except for the first one. I managed to retrieve the first language (en-us), but I also have the zh-CN Chinese pack installed on my operating s ...