Transforming JSON into a specialized text structure

After receiving JSON data from the server, I am required to convert it into a different format as shown below:

{"1":"82700","2":"26480","3":"31530","4":"22820","5":"15550","6":"205790"}

Although I have attempted to achieve this with the provided code snippet, it is not yielding the desired results. The current code iteration appears below:

       var cities = "{";

        for (var key in data.visits) {
            var val = data.visits[key];
            
            var obj = {};
            obj[val.City] = '' + val.Count;

            var code = '' + val.City;
            var count = '' + val.Count;

            cities += code + ':' + count + ',';
        }

        cities += "}";

The objective is to ensure that the integers are represented as strings and eliminate the trailing comma at the end of the collection. How can I rectify this code in order to accomplish the desired outcome?

Answer №1

Give this a try:

let data = {"visits":[{"City":6,"Count":5},{"City":16,"Count":1},{"City":23,"Count":1},{"City":34,"Count":1}]};
let result = {};

for (let i = 0; i < data.visits.length; i++) {
  result[data.visits[i].City] = String(data.visits[i].Count);
}

Check out the example here

Keys in an object always get converted to strings automatically, so you don't need to do it manually. If you need to convert the entire object to a JSON string, you can use JSON.stringify(result);

Answer №2

To generate a new JSON from an existing JSON, you can use parsing techniques and iterate through the data to construct the desired output. If you need more guidance, check out this helpful resource:

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 reason behind having to refresh my ReactJS page despite it being built with ReactJS?

I have developed a task management application where users can input notes that should automatically update the list below. However, I am facing an issue where the main home page does not display the updated todos from the database unless I manually refres ...

Is it possible to show an image without altering the Box dimensions?

Hi there, I am currently working on designing a footer and I have encountered an issue. I want to add an image in a specific position, but when I do so, it affects the size of the box. I was wondering if there is a way to set the image as a background or b ...

Search the database to retrieve a specific value from a multi-dimensional array

My database is structured as shown in the image below: https://i.sstatic.net/Flne8.png I am attempting to retrieve tasks assigned to a specific user named "Ricardo Meireles" using the code snippet below: const getTasksByEmployee = async () => { se ...

Tips for including a decimal point in an angular reactive form control when the initial value is 1 or higher

I am trying to input a decimal number with 1 and one zero like 1.0 <input type="number" formControlName="global_velocity_weight" /> this.form = this.fb.group({ global_velocity_weight: new FormControl(1.0, { validators: [Valida ...

Tips for triggering the .click() function upon returning to index.html after visiting a different page

I'm in the process of creating a portfolio website where the index.html page features a sliding navigation bar that displays a collection of projects. Each project is linked to a separate work.html page. I would like the sliding nav to automatically o ...

Display the user's username on the navigation bar once they have successfully

I am having trouble displaying the username after logging in on the navbar. After logging in with the correct credentials, I am redirected to the page, but the navbar doesn't update with the username. Can someone provide some tips on what I should do ...

Add a fresh category to a JSON document

Combining Express (Node.js) and Mongoose, I am developing a REST API and attempting to implement JWT token-based login. However, I have encountered an issue. Upon executing the code below: const mongoose = require('mongoose'); const User = mongo ...

Maximizing memory efficiency in Javascript through array manipulation strategy

In the project I am working on, I maintain a history of changes. This history is stored as an array containing objects, each with two arrays as properties. When adding a new history snapshot, it appears as follows: history.push({ //new history moment ...

Invoke the mounted lifecycle once more

At the moment, my table is set up to use the v-for directive to populate the data: <table v-for="(data, idx) in dataset" :key="idx"> </table> Following that, I have two buttons that perform actions in the database, and I wa ...

What could be causing the malfunction in this JavaScript and WebRTC code?

<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Vid Chat App</title> </head> <body> <video controls autoplay> </video> <script src="https: ...

Having difficulty scrolling down in a section with 100% height on iOS devices

Currently facing an issue with a website I am creating for my wedding invitation. The top section is set to have a 100% height and requires scrolling to view the rest of the content. While it functions perfectly on FireFox / Chrome on my computer, there s ...

Tips for preventing Unknown event codes in POST request responses

When my client makes POST requests to the nodejs server I am running, I receive "unknown event 72" messages in the POST response, as shown in the Wireshark screenshot below. These extra data points are causing unnecessary bandwidth usage for my application ...

Tips for adjusting the height of a fixed-size child element on the screen using only CSS and JavaScript restrictions

I am faced with a challenge involving two child elements of fixed size: <div class="parent"> <div class="static_child"> </div> <div class="static_child"> </div> </div> .parent { border: 1px solid black; dis ...

Receiving a JsonObject from a JsonArray loop is displaying a syntax error

JsonObject jObject = JsonObject.Parse(json); JsonArray jsonArray = jObject.GetNamedArray("records"); for (int index = 0; index < jsonArray.Count; index++) { JsonObject innerObject = jsonArray.GetObjectAt(index); data[index ...

Once the image is requested in HTML, three.js makes a subsequent request for the same image

This is a block of code. let image = new THREE.TextureLoader().load("http://odf9m3avc.bkt.clouddn.com/1493817789932.jpg") <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/88/three.min.js"></script> <img class='preLoad&apo ...

Is there a way to retrieve the previous URL using JavaScript?

Is there a way to retrieve the previous URL in a Next.js project? I came across this, but it always returns the base URL (http://localhost:3000/) when using document.referrer. Another approach I tried was pushing a state into window.history based on the of ...

Use a JSON file to dynamically define the file path for static assets in the index.html file of a React application

I am working on a solution to dynamically modify the file paths of static files (js & css) in the index.html file within my create-react-app. My goal is to have these paths directed to different sub-directories based on settings specified in a settings.jso ...

What is the process of transforming a Json raw object or property into a particular model?

public class DataTransfer { public object data { get; set; } public int Id { get; set; } = 0; public bool IsModified { get; set; } = false; public string tempData { get; set; ...

Transfer a value to the ng2 smart table plugin extension

Upon reviewing the document and source code related to pagination implementation in the (advanced-example-server.component.ts), I discovered that the ServerDataSource being used only supported pagination through HTTP GET (_sort, _limit, _page, etc paramete ...

Validate that a string is a correct file name and path in Angular without using regular expressions

Currently, I am using regex to determine if a string is a valid file name and path. However, when the string length becomes longer, it ends up consuming a significant amount of CPU, resulting in browser performance issues. public static readonly INVALID_F ...