Transform Array into JSON using AngularJS

My array consists of three elements

var data = [];
  data["username"]=$scope.username;
  data["phoneNo"]=$scope.phoneNo;
  data["altPhoneNo"]=$scope.altPhoneNo;

I need to send this data to the server in JSON format, so I used

    var jsonData = JSON.stringify(data);
    console.log("json data = "+jsonData);

However, the console is showing an empty array

json data = [] 

How can I properly convert this array into JSON?

Answer №1

It seems like you're trying to add elements to an array, but you're actually adding properties instead. If you try console.log(a.username);, you'll be able to see the value of your $scope.username.

You have a few options:

var a = [];
a.push({"username": $scope.username});
a.push({"phoneNo": $scope.phoneNo});
a.push({"altPhoneNo": $scope.altPhoneNo});

However, it looks more like you want to create an object:

var a = {};
a["username"] = $scope.username;
a["phoneNo"] = $scope.phoneNo;
a["altPhoneNo"] = $scope.altPhoneNo;

This way, a will be an object with properties. A cleaner version would be:

var a = {};
a.username = $scope.username;
a.phoneNo = $scope.phoneNo;
a.altPhoneNo = $scope.altPhoneNo;

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

How can you create an array in JavaScript?

Learning JavaScript has led me to discover the various methods for declaring arrays. var myArray = new Array() var myArray = new Array(3) var myArray = ["apples", "bananas", "oranges"] var myArray = [3] What sets them apart and which ways are typically ...

My goal was to alter the output for an array of objects

I needed to adjust the output for an array of objects. Here is my current result. I am looking to convert it into a specific format. let result = [ { team_id: 1, team_name: 'Avengers', participant1: 98, participant2: 99, par ...

Exploring the integration of Stripe Checkout with React and Express.js

Seeking assistance with integrating Stripe Checkout into my React application. I need to create a route in my nodejs/express server that will provide the session id required for setting up Stripe Checkout on the front end. The aim is to redirect users to s ...

In Chrome, the computed style of background-position is returned as 0% 0%

Let's say I have an element and I am interested in finding out its background-position: To achieve this, I use the following code snippet: window.getComputedStyle(element).getPropertyValue('background-position') If the value of background ...

What mistake am I making with arrays?

My understanding of JavaScript and Node.JS is still developing, so I'm puzzled as to why I'm receiving NaN when using this expression: var aUsersBetted = {}; aUsersBetted['1337'] += 200000; logger.debug(aUsersBetted['1337']); ...

Verification of the data entered in the input box

I am looking to develop an Input Box where users can enter the private details of a person. The first character must be either A or E, and the rest can be alphanumeric with no special characters allowed. I need to implement validation on the client side to ...

Ways to align and fix a button within a specific div element

How can I make the button with position: fixed property only visible inside the second div and not remain fixed when scrolling to the first or last div? .one{ height:600px; width: 100%; background-color: re ...

Securing the connection between clients and servers through encryption

For my mobile client, I am using Xamarin, with node.js as my backend and MongoDB as the database. The main issue I am facing is how to securely store user data in the database. If I only do server-side encryption, there is a risk of hackers intercepting th ...

Choose dropdown choices using Node.js, MySQL, and EJS

I am looking to create a dropdown list using data from my MySQL database. Specifically, I want to populate the names from the "customer" table in the select option of my "create budgets" form using EJS. However, I am encountering issues with passing EJS da ...

When refreshed using AJAX, all dataTable pages merge into a single unified page

I followed the instructions on this page: How to update an HTML table content without refreshing the page? After implementing it, I encountered an issue where the Client-Side dataTable gets destroyed upon refreshing. When I say destroyed, all the data ...

Using custom elements in both React and Angular is not supported

After successfully creating a custom element in React using reactToWebComponent, I integrated it into a basic HTML file like this: <body> <custom-tag></custom-tag> <script src="http://localhost:3000/static/js/bundle.js&quo ...

Leveraging Express.js alongside websockets

I am currently working on an application that is built on Expressjs and Angularjs. I am looking to incorporate a few two-way calls in addition to the existing HTTP calls. While I have gone through some websocket chat tutorials, none of them seem to be inte ...

How to properly implement search functionality in a React table?

I recently implemented a search feature for my table in React to filter items fetched from an external API. Instead of making repeated calls to the API on each search, I decided to store the retrieved data in two separate useState hooks. One hook holds th ...

Searching for the location of the apoc.conf within the Neo4j sandbox?

Just started using neo4j for the first time and I'm running it on my browser since my desktop version is not working. I'm trying to load JSON into it, but I keep getting an error message that says: Failed to invoke procedure `apoc.load.json`: Ca ...

The unexpected token "[ ]" was encountered while assigning a numerical value to an array

Hey everyone, I have a question that's been bothering me and I can't seem to find the answer anywhere. I'm currently learning pure JavaScript and although I am familiar with several other programming languages, I keep running into an issue ...

Identify the changed field using Javascript

In my MVC application, I have a form with multiple fields that I am monitoring for changes using JavaScript. The code snippet below keeps track of any changes made in the form: var _changesMade = false; // Flag the model as changed when any other fie ...

What is the best approach to dealing with "Cannot <METHOD> <ROUTE>" errors in Express?

Here is a simple example to illustrate the issue: var express = require('express'); var bodyparser = require('body-parser'); var app = express(); app.use(bodyparser.json()); app.use(errorhandler); function errorhandler(err, req, res, ...

Sort activities according to the preferences of the user

This is the concept behind my current design. Click here to view the design When making a GET request, I retrieve data from a MongoDB database and display it on the view. Now, I aim to implement a filter functionality based on user input through a form. ...

Running Javascript through Selenium with Python while using Tkinter for the GUI

Hey there! I am currently working on a project where I am developing a website using Selenium WebDriver integrated with a Tkinter GUI. In the GUI, I have an entry field and a button. When I enter a URL in the field and click the button, the web browser ope ...

Converting Emoji to PNG or JPG using Node.js - What's the Procedure?

Currently, I am working on a project that requires me to create an image file from emoji characters, preferably using Apple emoji. Initially, I thought this task would be simple to accomplish, but I have encountered obstacles with each tool I have tried. ...