Turning variables into a JSON string using the JSON stringify method

Currently, I am working with JSON stringify and here is the code snippet:

var myObject = {};
    for(var i=0; i < arr.length; i++){
        myObject[i]=[];
        //myObject[i].push('image:'+arr[i].id);
        myObject[i].push('nick:'+arr[i].nick); 
        myObject[i].push('phone number:'+arr[i].tlfno);
        myObject[i].push('name:'+arr[i].nombre);
        myObject[i].push('description:'+arr[i].descripcion);
        myObject[i].push('address:'+arr[i].direccion);
        myObject[i].push('date:'+arr[i].fecha);
        myObject[i].push('state:'+arr[i].estado);
        myObject[i].push('image type:'+arr[i].tipoimagen);
        //myObject[i].push('image:'+arr[i].imagen);
    }
    var jsonData = JSON.stringify(myObject);
    console.log(jsonData);

The output that I am receiving is as follows:

{"0":["nick:pepe","phone number:678909897","name:dsfdfsf","description:dsdsdsd","address:fdfdf","date:fdfdf","state:1","image type:image/jpeg"]

However, this is not correct. The desired output should look something like this:

{"0":["nick":"pepe" including double quotes. Can anyone assist in achieving this? Thank you.

Answer №1

It seems like you are attempting to add objects, not just strings, to the array.

list[i].push( {name: arr[i].name} );

This would result in something similar to

{"0":[{"name":"john"}]}

Keep in mind that {"0":["name":"john"... is invalid syntax, so you won't see that output

FIDDLE

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

Key in the calculation on Keypup for multiple rows, one row at a time

I want to create a calculation function for a form with multiple rows. The goal is to determine the totals for each row by multiplying the cost and unit price, then inputting the result in the total field. Below is the script that I attempted: <scrip ...

The rule 'react-hooks/exhaustive-deps' does not have a defined definition

I received an eslint error message after inserting // eslint-disable-next-line react-hooks/exhaustive-deps into my code. 8:14 error Rule 'react-hooks/exhaustive-deps' definition not found I tried to resolve this issue by referring to this p ...

The illumination in Three.js is dynamic and ever-changing

I'm currently working on creating static light that remains constant regardless of camera movement, and I need to retrieve the actual position of the light within the fragment shader. Here is my current setup: scene = new THREE.Scene(); camera = ne ...

The Laravel API request made via AJAX is returning an abundance of unnecessary data

Here is my JavaScript code for the button handler: $("#get-password").on("click", () => { $.get("https://psycho.bulash.ru/api/get.password").done( (data) => { console.log(data); } ); } ...

When the forward button is pressed multiple times in the carousel, the alignment changes

I recently noticed that the alignment of my carousel gets disturbed when I repeatedly click the forward button (>). How can I ensure that the carousel moves smoothly one item at a time when I click the forward or backward buttons? <div class="contai ...

Is the HTTP request from the browser being recorded?

When sending an HTTP request using fetch to website A from the Chrome console on website B, is it possible for website B to track any information about that request, or is it strictly client-side? In other words, can website B detect this action? Thank yo ...

Experiment with a ThreeJS, Websockets, and NodeJS Client/Server Interaction

Exploring the possibilities of socket.io, ThreeJS, Javascript, and NodeJS, I embarked on a project to create a simple client/server setup using ThreeJS's graphics. While uncertain if these frameworks would seamlessly integrate, I decided to take a cha ...

When attempting to parse a JSON string with Newtonsoft, it results in a null reference exception being raised

I need help parsing this JSON string: { "layers":[ { "metadata":{ "cells":2, "records":42887000, "dataset":"uk_da", "query":"155ms", "sample":10, "calibrate":100 } }, { "lookups":{ ...

Tips for converting an npm module into a browser-ready script

Looking to enhance the functionality of the Parse SDK by customizing it. The provided source can be accessed through an npm module, enabling usage in node environments. Wondering how to transform this node module into a standalone parse.js script that wil ...

What is the best way to transfer data from a custom method and use it in another method within my constructor function in Javascript?

As I pondered a suitable example, I devised a constructor function centered around precious metals. This function accepts the type of metal and its weight as parameters. Within this constructor, there are two methods: one to verify if the precious metal (g ...

Here's a way to programmatically append the same icon to multiple li elements generated using document.createElement:

I am new to creating a to-do app and need some guidance. When a user enters a task, I successfully create a list item for that task. However, I am unsure how to add a delete icon next to the newly created li element. Can someone please help me out? Below ...

While attempting to code a pop up search bar with HTML, CSS, and JavaScript, I encountered an issue where an error was displayed on the console

<form action="" class="search-form"> <input type="search" id="search-box" placeholder="search here..."> <label for="search-box" class="fa fa-search" aria-hidden=&q ...

Incorporating a feature to leave comments in JSON data through AngularJS

Yesterday, I completed an AngularJS test that presented me with two tasks. One task involved displaying the data of a JSON file on a webpage in HTML form. I accessed the FreshlyPressed JSON via the link "" and effectively showcased the thumbnail, pos ...

Newbie to Next-JS exploring the use of two dynamic APIs, with successful integration of one while encountering difficulties with the other

I recently received help from a friend to transform my inefficient JS web app into a next-app. However, as I attempted to progress further, I encountered various obstacles and found myself feeling lost. Within my project, I have developed two APIs that fe ...

What steps can I take to combine the values from an array of dictionaries?

Here is my current data: a = [{"country":"Colombia","date":"1995"}, {"country":"China","date":"1995"},{"country":"USA","date":"1992"}] ...

Using a for loop in JavaScript to fetch and display a specified number of results from an API

Recently, I delved into the world of Javascript and API arrays to grasp the concept of retrieving and manipulating various APIs. The topic of Javascript loops and arrays has been discussed numerous times, both here on StackOverflow and on other platforms. ...

What steps should I take to convert a dynamic JSON into a Java class?

Recently I have encountered a JSON request coming from a service that contains multiple data entries. { dataPair { keyA : valueA keyB : valueB .... } name: string addr: string } } In my original setup, I had the ...

Sort out the information in the table

Seeking assistance on how to filter a table based on certain conditions. Refer to the sample image provided in the link below: https://i.sstatic.net/Egvj6.png Here is the code I have attempted: this.reportData.filter(it => { if ( ...

How can the onclick event be activated by pressing the enter key with inline javascript?

[FYI: I am not permitted to alter the existing markup. The div will be clicked, not a button or anchor] I have a menu that needs to comply with accessibility standards and open its submenu upon being clicked. This onclick function needs to be triggered w ...

Having trouble initializing an array of objects to store data in MongoDB using AngularJS

I am facing an issue while trying to save dynamically created HTML in MongoDB using Mongoose from AngularJS. The problem lies in creating the required object that matches the Mongoose schema I have defined. model code var SegmentSchema = new Schema({ n ...