What is the best way to integrate a loop in JavaScript to retrieve values?

<script>
var data={ 
    Data: { 
        name: 'aaaa',
        number: '0003'
    },
    values: { 
        val: '-20.00',
        rate: '22047' 
    },
    user: [ '6|1|5', '10|1|15' ] 
};

console.log(data);
console.log(data.user.length);
for(var i=0;i<data.user.length;i++) {
    console.log(data.user[i]);
}
</script>

Here is the code showcasing a data structure with nested objects and an array. It logs the elements in the "user" array.

The contents of the "user" array are as follows: user: [ '6|1|5', '10|1|15' ]

However, there is a requirement to display the data in a different format:

  • userid - 6
  • roolno - 1
  • rank - 5


  • userid - 10

  • roolno - 1
  • rank - 15

If you need assistance in achieving this transformation, feel free to ask for help.

Answer №1

If you need a straightforward solution, consider using a basic map function like in this example on plunker:

data.user.map(function(x) { 
    var parts = x.split('|');
    return {
        userid: parts[0],
        roolno: parts[1],
        rank: parts[2]
    };
});

Executing the above code snippet would provide you with the following output:

[
    {
        userid: 1,
        roolno: 1,
        rank: 5
    },
    {
        userid: 10,
        roolno: 1,
        rank: 15
    },
]

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

When transitioning an iOS Swift app to the background, a NodeJS error arises: 'Headers cannot be set after they have been sent to the client'

My app is built using Swift/SwiftUI. I utilize the ObservableObject and JSONDecoder to retrieve data from my Node.JS Express API and display it within the app: struct DevicesList: Decodable { var data: [DeviceInfo] } struct DeviceInfo: Decodable { ...

"Running experiments with Google Ads and Google Analytics scripts results in a blank page being displayed

Currently, I am working on a plain HTML file and conducting tests to ensure that the Google Ads and Analytics scripts are functioning correctly before implementing them on other pages. A colleague who has an AdSense account provided me with the script code ...

Steps for clearing a set of checkboxes when a different checkbox is selected

While working on a website I'm developing, I encountered an issue with the search function I created. The search function includes a list of categories that users can select or deselect to filter items. This feature is very similar to how Coursera has ...

Ways to set each tinymce editor as standard excluding a few selected ones

Currently, I am utilizing TinyMCE as my text editor for a specific project. Within the header of my codebase, I have specified that all <textarea> elements should be rendered with TinyMCE functionality. By default, these text areas have a height of 3 ...

Converting Cookies to Numeric Values in JavaScript: A Step-by-Step Guide

I'm currently developing a cookie clicker website and am encountering an issue with saving the user's score to localstorage when they click the "save" button. Here is what my code looks like: let score = 0; function addPoint() { score += 1; } ...

Ways to delete an attribute from a DOM element with Javascript

My goal is to use JavaScript to remove an attribute from a DOM node: <div id="foo">Hi there</div> First, I add an attribute: document.getElementById("foo").attributes['contoso'] = "Hello, world!"; Then I attempt to remove it: doc ...

Can native types in JavaScript have getters set on them?

I've been attempting to create a getter for a built-in String object in JavaScript but I can't seem to make it function properly. Is this actually doable? var text = "bar"; text.__defineGetter__("length", function() { return 3; }); (I need th ...

Guide on transferring Context to the loader in React-Router-6

In my development setup, I am utilizing Context for managing the global loading state and React-router-6 for routing. My approach involves incorporating loader functionality in order to handle API requests for page loading. However, a challenge arises when ...

Extract the String data from a JSON file

valeurs_d = ""; for (var i = 0; i < keys.length -1 ; i++) valeurs_d += + event[keys[i]] + ", "; var str5 = ","; var str6 = str5.concat(valeurs_d); var valeurs = str6.sub ...

Creating a JSON array using looping technique

I am attempting to construct a JSON array using a loop where the input className and value will serve as the JSON obj and key. However, I am facing difficulties in creating one and cannot seem to locate any resources on how to do so. Below is an example sn ...

Using jQuery to attach events and trigger them

Within my code, I have the following scenarios: $("#searchbar").trigger("onOptionsApplied"); And in another part of the code: $("#searchbar").bind("onOptionsApplied", function () { alert("fdafds"); }); Despite executing the bind() before the trigge ...

Mongoose virtual population allows you to fetch related fields

When attempting to utilize virtual populate between two models that I've created, the goal is to retrieve all reviews with the tour id and display them alongside the corresponding tour. This is achieved by using query findById() to specifically show o ...

Unable to use console log in shorthand arrow function while working with Typescript

When debugging an arrow function in JavaScript, you can write it like this: const sum = (a, b) => console.log(a, b) || a + b; This code will first log a and b to the console and then return the actual result of the function. However, when using TypeSc ...

- Determine if a div element is already using the Tooltipster plugin

I have been using the Tooltipster plugin from . Is there a way to check if a HTML element already has Tooltipster initialized? I ask because sometimes I need to update the text of the tooltip. To do this, I have to destroy the Tooltipster, change the tit ...

Cover any HTML element with a translucent overlay box

I have a unique problem with an HTML file that is out of my control when it comes to its content. My only option is to inject a CSS file and/or JavaScript (potentially using libraries like jQuery) into the mix. Within this HTML, there are elements that re ...

This function is designed to only work under specific conditions

Looking for assistance with a function that takes an item ID as input and changes its border when pressed. The goal is to increase the border width by 2px when there is no border, and remove the border completely when pressed again. Currently, only the f ...

Mastering the art of MUI V4: Implementing conditional row coloring

I've encountered an issue with my basic Material UI v4 datagrid. I'm attempting to change the color of any row that has an age of 16 to grey using color: 'grey'. However, I'm finding it challenging to implement this. The documentat ...

White border appears when hovering over MUI TextField

I've been troubleshooting this issue for what seems like an eternity. I've combed through Chrome's inspect tool, searching for any hover styles on the fieldset element, but to no avail. Here's my dilemma... I simply want a basic outline ...

Utilizing ng-options within an ng-repeat to filter out previously chosen options

Facing a simple problem and seeking a solution. I am using ng-repeat to dynamically create select boxes with ng-options displaying the same values. The ng-repeat is used to iterate through model options. <div data-ng-repeat="condition in model.condit ...

The speed at which Laravel loads local CSS and JS resources is notably sluggish

Experiencing slow loading times for local resources in my Laravel project has been a major issue. The files are unusually small and the cdn is much faster in comparison. Is there a way to resolve this problem? https://i.stack.imgur.com/y5gWF.jpg ...