JavaScript code to change an array into a stringified format

I have encountered a challenge with transforming an array. The original array looks like this:

   array =  [
    {
        "name": "name",
        "value": "Olá"
    },
    {
        "name": "age",
        "value": "23"
    },
    {
        "name": "isVisible",
        "value": "1"
    }
]

The goal is to convert it into the following string format:

"{\"name\":\"Olá\",\"age\":123,\"isVisible\":true}"

Despite attempting various methods, I have not been successful in achieving this. My most recent attempt was as follows:

array = array.map((p) => {
          return Object.values(p).join(':').replace(/\[/g, '{').replace(/]/g, '}').toString();
        }),

Any suggestions or solutions would be greatly appreciated.

Answer №1

To easily convert an array into a JSON string, start by creating an empty object. Then loop through the array to populate the object with key-value pairs. Finally, use JSON.stringify(obj) to generate the desired result.

Here is an example:

var obj = {};
array =  [
    {
        "name": "name",
        "value": "Bonjour"
    },
    {
        "name": "age",
        "value": "30"
    },
    {
        "name": "isVisible",
        "value": "0"
    }
]

for(let item of array) {
    obj[item.name] = item.value;
}

const jsonString = JSON.stringify(obj);
console.log(jsonString);
/*
output : "{\"name\":\"Bonjour\",\"age\":123,\"isVisible\":false}"
*/

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

Combining two sets of data into one powerful tool: ngx-charts for Angular 2

After successfully creating a component chart using ngx-charts in angular 2 and pulling data from data.ts, I am now looking to reuse the same component to display a second chart with a different data set (data2.ts). Is this even possible? Can someone guide ...

Leveraging ng-click and ng-hide/show directives within ng-repeat in Angular

I have a simple Single Page Website built with Angular. I utilized ng-repeat to generate content on the main page, where each item is an image. I am looking to create an alternate view for each image to display more details. I have implemented this feature ...

The Angular Google Maps Directive zooms in too much after the "place_changed" event has fired

Currently, I am developing a store locator app for DHL accessible at storefinder.hashfff.com/app/index.html For this project, I decided to utilize the angular-google-maps library for its features. However, in hindsight, working directly with the Google Ma ...

Accessing the path to an imported file in Node.js

Currently, I am working on a parser and encountering imports such as ../modules/greeting.js. Additionally, I have an absolute path to the file from where I performed the import: C:\Desktop\Folder\src\scripts\main.js. I am seeking ...

Twitter API causing issues with setTimeout function in Node.js

Attempting to read from a file and tweet the contents in 140 character chunks, one after the other has proven to be quite challenging. Despite verifying that other parts of the code are functioning correctly, using a simple for-loop resulted in tweets bein ...

Issue: ui-route failing to function properly when the href attribute is utilized

I am currently working on implementing ui-route to manage the states of my app while focusing on URL navigation. My goal is to enable users to simply click on a link and be directed to the state associated with the specific URL. After following an In-Dep ...

Troubleshoot: Issue with Navbar Dropdown Expansion on Bootstrap Sass 3.3.6 with JavaScript

Beginner: Bootstrap Sass 3.3.6 - Incorporating Javascript - Issue with Navbar Dropdown Not Expanding application.html.erb Head: <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %> ...

Utilizing category-based data filtering in a React functional component

This is my first venture into ecommerce projects using React.js. I've set up a product listing with categories displayed on the left side, as shown in the screenshot below. The goal is to filter products based on category. I'm almost there, bu ...

Counting Clicks with the Button Counter

I'm having an issue with my jQuery code that is supposed to count button clicks - it stops after just one click. I need help fixing this problem. $(function() { $('.btn').click(function() { $(this).val(this.textContent + 1); }); } ...

Confusing postback phenomena in ASP.NET web forms

I have developed a small script that successfully maintains the focused element during an async postback. However, I encountered an issue when tabbing through controls generated inside an asp:Repeater, where a full postback is unexpectedly triggered. Below ...

Effortlessly uploading large files using axios

I am currently facing an issue and I am seeking assistance. My goal is to implement file chunk upload using axios, where each chunk is sent to the server sequentially. However, the requests are not being sent in order as expected. Below is a snippet of m ...

Using MongoMapper with Rails to efficiently render arrays in views

In my Rails application, I have a controller that retrieves data from MongoDB. The specific field I need is actually an array, and I want to display it in an erb view. Currently, my workaround involves setting the JavaScript variable directly in the view ...

Make Fomantic-UI (Angular-JS) sidebar scroll independently

Is there a way to make a sidebar scroll independently of the content it pushes? Currently, my page is structured like this: -------------------------- |[button] Header | -------------------------- |S | Main content | |i | ...

Struggling with implementing Angular and TypeScript in this particular method

I'm dealing with a code snippet that looks like this: myMethod(data: any, layerId: string, dataSubstrings): void { someObject.on('click', function(e) { this.api.getSomething(a).subscribe((result: any) => { // ERROR CALL 1. It ...

Display information using an ASP.Net barcode scanner

Currently, I am developing a WCF service application that involves receiving characters from a barcode reader and displaying the data on the UI for the user. My issue arises when inputting data using the keyboard into a textbox; everything functions corr ...

Having trouble getting the group hover animation to function properly in Tailwind CSS

Just starting out with tailwind css and running into a little issue. The hover animation I'm trying to apply isn't working as expected in this case. Instead of seeing the desired animated background when hovering over the group, it seems the back ...

"Flashes of canvas in constant motion between animated scenes

I have a practical exercise to do for school, but I am very new to HTML/JS. The issue I am facing is that my canvas is flashing, like it erases one image and then quickly displays another. I want both images to be displayed at the same time. Here is the co ...

Resolved plugin issue through CSS adjustments

Take a look at this template 1) After referring to the above template, I developed a fixed plugin using JavaScript. 2) Clicking the icon will trigger the opening of a card. 3) Within the card, I designed a form using mdb bootstrap. Everything seems to ...

Is it possible to create multiple text input components using the "each" function, and how can I update the state by combining all of them together?

I am looking to create a text-based word game where the length of each word changes with every level. Each letter will be placed in its own box, forming a matrix (e.g. 10 words, length: 10 => 10x10 matrix). How can I generate multiple text input componen ...

"Passing data from a child component to a parent component using Vue's emit

offspring template: ` <li v-for="option in listaOptiuni" :key="option.id"> <input @change="updateSelectAllToateOptiunile(); sendListaToateOptiunile()" v-model="listaToateOptiunile" :value="o ...