Convert a single object into a JSON string representation on each line

Can you convert the following data into the desired format through stringification?

Data:

let result = JSON.stringify([
   {
     "Color": "Red", 
     "Type":"Fast"
   },
   {
     "Color": "Blue", 
     "Type":"Slow"
   }
]);

Desired output:

[
   {"Color": "Red", "Type":"Fast"},
   {"Color": "Blue", "Type":"Slow"}
]

Answer №1

To achieve the desired outcome, iterate through each item separately and convert them to strings before combining them with a line break:

const items = [
   {"Fruit": "Apple", "Color":"Red"},
   {"Fruit": "Banana", "Color":"Yellow"}
];

const output = "[\n" + items.map(item => '  ' + JSON.stringify(item)).join(',\n') + "\n]";

console.log(output)

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

Switching the URL without reloading the page in NEXT.JS

Currently, I am in the process of building an ecommerce store using NEXT.JS and Redux. Within the product listing page, I have incorporated a sorting select dropdown featuring options such as Price Low to High, Price High to Low, and New Arrivals. My goal ...

Dealing with error management in Transfer-Encoding chunked HTTP requests using express and axios

My current challenge involves fetching a large amount of data from a database in JavaScript using streaming to avoid loading all the data into memory at once. I am utilizing express as my server and a nodeJS client that retrieves the data using Axios. Whil ...

Operators within an observable that perform actions after a specific duration has elapsed

Is there a way in an rxjs observable chain to perform a task with access to the current value of the observable after a specific time interval has elapsed? I'm essentially looking for a functionality akin to the tap operator, but one that triggers onl ...

What could be causing my browser to not respond to the JavaScript function for clicking?

I have been struggling to get the images on my browser to change when I click on them. Despite my efforts, I haven't found a solution yet... I've experimented with changing the variables to ".jpg" and also tried removing them altogether. var ...

Importing a 3D Model Using Three.js

I've been trying to import a 3D model by following tutorials. I managed to successfully import using A-Frame Tags, but encountering issues with Three.js. The code snippets are from a tutorial on YouTube that I referred to: https://www.youtube.com/watc ...

How to use JavaScript to read gzip files from a Node.js/Express server

A service built in .NET is exporting *.gz files to a nodejs server. These files contain gziped json strings. Below is the route defined in Node.js for saving the files locally: router.post("/", function (req, res) { var filePath = path.join(__dirname ...

Refresh Chart Information using Ng2-Charts in Charts.js

Utilizing chart.js and ng2-charts, I am developing gauge charts for my platform to monitor the fluid levels inside a machine's tank. The values are retrieved from an external API, but I am encountering an issue where the charts are rendered before I ...

Move images horizontally next to the height of an element

I am attempting to increase the top attribute in relation to the element it is currently adjacent to. The element should only scroll directly next to the other element and cease when it surpasses the height of that element. My Goal: I want the image to re ...

The PHP page is not receiving the variable passed through AJAX

Within the following code snippet, there seems to be an issue with accessing the dataString variable in the comment.php page. To retrieve the variable name, I utilized $_POST['name']. $(document).ready(function(){ $("#submit").click( function() ...

Tips for Displaying and Concealing Tables Using Radio Buttons

Does anyone know how to refactor the jQuery code to toggle between two selection options (Yes and No)? This is the jQuery code I have tried: $(document).ready(function() { $("#send_to_one").hide(); $("input:radio[name='decision']").chan ...

Generate three random names from an array and assign them to an element

This website is amazing! I've interacted with so many awesome people here! Currently, I have successfully implemented code to get one random name from an array. However, I now want to display three different names each time, and I'm facing a roa ...

Improving the visualization of large GPS tracks on Google Earth Plugin

I need to display GPS routes on Google Earth using the Google Earth API. However, with approximately 20,000 points per route, the performance is not optimal. The code I have implemented successfully draws the tracks but struggles with rendering time and tr ...

In Javascript, where are declared classes stored?

When working in a browser environment like Firefox 60+, I've encountered an issue while attempting to retrieve a class from the global window object: class c{}; console.log(window.c); // undefined This is peculiar, as for any other declaration, it w ...

Retrieving ID of an element to be animated with jQuery

I have a sprite image that changes background position when hovered over, and while it's currently working, I'm looking for a more efficient way to achieve this. I need to apply this effect to several images and am exploring ways to avoid duplica ...

Create automatic transcripts for videos, including subtitles and captions

Are there any tools or plugins available that can automatically create a transcript of a video for website playback? For example, generating captions and subtitles in the English language. ...

Troubleshooting a React Node.js Issue Related to API Integration

Recently, I started working on NodeJs and managed to create multiple APIs for my application. Everything was running smoothly until I encountered a strange issue - a new API that I added in the same file as the others is being called twice when accessed fr ...

Interested in learning how to redirect to a different page using vanilla JavaScript after submitting an HTML form with a Django backend?

Recently delving into Django, I encountered a challenge of linking a js file to my HTML form page and saving the form data before moving on to the next screen. My aim was to incorporate a feature where users can click a picture and POST it along with their ...

Vue - making one element's width match another element's width

Trying to dynamically adjust the innermost element's width to match the outermost element's width with Vue: <div id="banner-container" class="row"> <div class="col-xs-12"> <div class="card mb-2"> <div ...

Utilizing hyperlinks to dynamically remove elements from a webpage with the power of HTML5 and JavaScript

Looking for guidance on how to create a link that will remove two specific list items from an unordered list located above the link. As a beginner, any assistance is greatly appreciated! ...

Converting JSON object to a string

I have an object that contains the value "error" that I need to extract. [{"name":"Whats up","error":"Your name required!"}] The inspector displays the object in this format: [Object] 0: Object error: "Your name required!" name ...