The process of embedding variables within a JSON Array function in JavaScript

As a newcomer to JavaScript, I am facing an issue while trying to create a simple program. I am attempting to store the variables 'name', 'document', and 'code' inside the JSON array called 'records'.


var records = [];
var code = 1;

function save() {
    var name = document.getElementById("pName").innerText;
    var doc = document.getElementById("pDocument").innerText;
    
    var record = {
        code: 0,
        name: "",
        sex: ""
    };
    
    record.push(code, name, doc);
}  

Answer №1

To make adjustments to the salvar() function, you can specify each value of your "registro" variable like so:

var registro = [{
    codigo: codigoValue,
    nome: nomeValue,
    sexo: ""
}];

After that, use the push() function to add "registro" into the "registros" array. The revised code would look like this:

var registros = [];
var codigoValue = 1;
function salvar() {
    var nomeValue = document.getElementById("pNome").innerText;
    var documento = document.getElementById("pDocumento").innerText;
    var registro = [{
        codigo: codigoValue,
        nome: nomeValue,
        sexo: ""
    }];
    registros.push(registro);
}

Answer №2

When working with arrays in JavaScript, it's important to pay attention to the property/value structure. In your code snippet, you have assigned values to a variable called registro instead of registros.

Furthermore, the registros variable seems to be unused in your code.

To correct this issue, follow these steps:
  1. First, create an array variable named registros
  2. Next, define a function called salvar
  3. Inside the salvar function, create an object that will store your values. For example, you can create an object with a property named "nome" and assign it the value fetched from document.getElementById("pNome").innerText.
  4. Finally, push the created object into the registros array
var registros = [];
var codigo = 1;
function salvar() {
    var nome = document.getElementById("pNome").innerText;
    var documento = document.getElementById("pDocumento").innerText;
    var obj = { nome, documento, caodigo}

    registros.push(obj);
}

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

Exploring the parsing of nested JSON in Android using Kotlin

As I am relatively new to Kotlin programming, I'm facing difficulties in parsing JSON data. My goal is to extract "title" and "body" from the "notification" within the "unackd" array only. This is my current implementation: private fun parse(): Bool ...

What is the best way to toggle dropdown menu items using jQuery?

Upon clicking on an li, the dropdown menu associated with it slides down. If another adjacent li is clicked, its drop down menu will slide down while the previous one slides back up. However, if I click on the same li to open and close it, the drop down m ...

Locate the highest and lowest values within a .json file

When working on a graph using d3.js, one key step is setting up the scales for the axis. The data for the graph is stored in a Json file with multiple arrays, each representing different regions and years: [{ "id" : "AustraliaNewZealand" , "year" ...

Converting a Pandas dataframe to JSON format: {name of column1: [corresponding values], name of column2: [corresponding values], name

I'm a beginner in Python and pandas. I've been attempting to convert a pandas dataframe into JSON with the following format: {column1 name : [Values], column2 name: [values], Column3 name... } I have tried using this code: df.to_json(orient=&apo ...

Obtaining information through a search form and utilizing a JSON API URL to gather data

Currently, I am in the process of compiling a list of hotels through the Expedia API . I have obtained a json output of hotel listings from the specified URL: API Sample Using a simple foreach loop, I am able to display the hotels retrieved from the abov ...

Check my Twitter feed every 10 seconds

I'm attempting to access my Twitter feed (sent from a smartphone) for a local application, as Twitter is remote... I created a jQuery + JSON script, but with my overly frequent setInterval at 25ms, I quickly hit the limit of 150 requests per hour and ...

Personalize the loading bar using JavaScript

Currently, I am utilizing a basic progress bar from Bootstrap. However, I have the desire to design a custom progress bar similar to this: Unfortunately, I am uncertain about how to create such a unique progress bar. Perhaps there is an existing JavaScri ...

Can halting an ajax function mid-process prevent it from finishing?

My objective is to convert a video using ffmpeg, which tends to take a considerable amount of time to complete. I'm considering sending an ajax request to the server for this task, but I don't want the user to have to wait until the video convers ...

Experimenting with altering the heights of two Views using GestureHandler in React Native

I am currently working on a project where I need to implement height adjustable Views using React Native. One particular aspect has been causing me some trouble. I'm trying to create two stacked Views with a draggable line in between them so that the ...

Extracting multiline value from a textarea using JavaScript

I'm trying to extract a multiline value from a textarea using JavaScript or jQuery and store it in a cookie. Below is the code snippet I am using: HTML: <textarea id="cont" cols="72" rows="15"> JavaScript: var txt = $('#cont').val( ...

The functionality of the Bootstrap carousel for moving to the next and previous images is malfunctioning, as it only

The carousel on my website is not functioning properly. It only displays the first image and does not slide to the next pictures as it should. Here is the code snippet for the carousel: <body> </nav> <div id="carousel1" class="carousel slid ...

What is the process for implementing an image as the background instead of a color for each column in a Google chart?

I'm currently working with Google Chart and I have set up a column chart. However, I am looking to display a background image instead of a background color in each column. Is this achievable with Google Chart? If so, how can I accomplish this? If anyo ...

React is unable to identify the `initialValue` attribute on a DOM element

Warning: React is not able to recognize the `initialValue` property on a DOM element. If you intended for it to show up in the DOM as a custom attribute, use `initialvalue` in lowercase instead. If it was mistakenly passed from a parent component, make sur ...

The TypeScript compiler generates a blank JavaScript file within the WebStorm IDE

My introduction to TypeScript was an interesting experience. I decided to convert a simple JavaScript application, consisting of two files, into TypeScript. The first file, accounts.ts, contains the main code, while the second one, fiat.ts, is a support f ...

In a multi-user environment, querying FaunaDB may not always retrieve the most up-to-date results

Background I've been delving into FaunaDB alongside React and managed to create some code with inspiration from this article. The project I'm working on involves a coffee poll/counter app - users are presented with various types of coffee and ca ...

Having trouble retrieving a dynamic name with Formcontrol error?

I keep encountering a typeError in this section of code <p *ngIf="formValue.controls['{{obj.name}}'].invalid, but when I manually enter it like this *ngIf="formValue.controls['uname'].invalid it works perfectly fine. What ...

What could be the reason for the appearance of Next.js compile indicator in my final production build?

Upon completing the development and deployment of a Next.js website, I observed that the black compile indicator continued to appear in the bottom-right corner of my browser, similar to its presence during local development. The indicator can be viewed he ...

Encountered an unexpected symbol < in JSON while implementing fetch() operation

I'm currently working on linking my React signup page to my Django API in order to automatically create a user profile in Django when a user signs up. Whenever I attempt to create a new user, I encounter this error in my console: Signup.js:33 ...

Changing the direction of scrolling in AngularJS

I'm currently working on an Ionic / Angular application and I've come across a situation where I need to change the scroll direction when scrolling. Usually, when you scroll down, the content moves down as well. However, I want to achieve the opp ...

Enhancing Grails dynamic dropdown to include a pre-selected value in edit.gsp

One feature I have implemented is a dynamic dropdown menu in my _form.gsp file that appears in both the create and edit pages. While it currently works as intended, I am seeking a way to display the selected value on the edit page. _form.gsp <g:s ...