What is the best way to save a key and its corresponding value into an array storage?

Storing input data in an object with key-value pairs like so:

const object1 = {
    un: inp.value,
    pw: inpw.value
};
var myJSON = JSON.stringify(object1);
var myObj = JSON.parse(myJSON);

Now, I aim to store each object in an array. For example, the first input would look like:

  • {"un":"john","pw":"smith"}

This would be stored in array[0].

The second input could be something similar:

  • {"un":"beth","pw":"sebastian"}

And so forth..

Accessing array[0] should only display {"un":"john","pw":"smith"}'

Here is the code snippet:

<form action="" autocomplete="on">
  <div class="" style="width:300px;">
    <input id="myInput" type="text" name="myInput" placeholder="Input" autocomplete="input">
    <input id="myPW" type="password" name="myPassword" placeholder="Password" autocomplete="password">
  </div>
  <input id="button" type="submit">
</form>

    <h2>Username</h2>
    <p id="uname"></p>

    <h2>Password</h2>
    <p id="pass"></p>

    <h2>Data</h2>
    <ol id="val"></ol>

    <h2>Array</h2>
    <ol id="arr"></ol>

<script>
var myButton = document.getElementById('button');
var inp = document.getElementById('myInput');
var inpw = document.getElementById('myPW');

myButton.addEventListener('click', function(event) {
    event.preventDefault();

    const object1 = {
        un: inp.value,
        pw: inpw.value
    };
    var myJSON = JSON.stringify(object1);
    var myObj = JSON.parse(myJSON);

    val.innerHTML += '<li>' + myJSON + '</li>';


    // This is where we add the myJSON to the cookies array
    cookies = [];
    cookies.push(myJSON);
    for (var i = 0; i < cookies.length; i++) {
        arr.innerHTML += '<li>' + cookies[i] + '</li>';
    }       
});

How can I resolve this issue?

Answer №1

To store values, simply create an array and add the values to it:

let dataArr = [];

let jsonData = JSON.stringify(dataObject);
let objData = JSON.parse(jsonData);

dataArr.push(objData);

Check out the code on JSfiddle: https://jsfiddle.net/Jk4l8h9g/2/

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

Adding options to a select input after making an ajax request

I have a dropdown menu. Whenever it is changed, the following code is executed: $('#type').change(function() { var selectedYear = $("#year option:selected").val(); var selectedProduct = $("#product option:selected").val(); var select ...

Insert unpredictable numerical values for missing data in a NumPy array

Recently, I encountered a challenge with a NumPy array X that contains some 'nan' values. X = np.array([[ 1., 2., 3.], [ 4., nan, 54.], [ 90., 32., nan], [ 55., 42., 86.]]) My goal is to rep ...

Exploring Angular 6 with Universal Karma for effective module testing

Issue I have been facing challenges while testing my Angular 6 application with Karma. I am encountering errors such as: Can't bind to 'ngModel' since it isn't a known property of 'mat-select'. Although the import works in ...

Struggling to adjust the timeout to exceed 60 seconds

I have been attempting to set a timeout for 120 seconds or more, but no matter what I try, the requests are timing out after only 60 seconds. Things I have tried include: $.ajax({ url: URL, timeout: 120000, success: function(html){ co ...

Issues with external javascript link functionality

I'm having trouble connecting my external JavaScript file to my HTML code. I'm attempting to concatenate two strings using an input function and then display the new string in the empty text field. What could be causing this issue? Appreciate an ...

Error: A WriteConflict has occurred because this operation conflicted with another. Please try your operation again or consider using a multi-document transaction

Whenever I attempt to update only 2 documents with a transaction, my logs frequently show the following error: MongoServerError: WriteConflict error: this operation conflicted with another operation. Please retry your operation or multi-document transactio ...

Token does not function properly on Fetch request sent to PHP script

I have a pair of files: one is revealing a session token, while the other is responding to a javascript fetch. The first file goes like this: <?php session_start(); unset($_SESSION['sessionToken']); $_SESSION['sessionToken'] = vsprin ...

What is the best way to link a JavaScript file from a node package in an HTML document?

After developing a Node.js Express App using JetBrains WebStorm, I utilized npm (via File->Settings->Node.js and NPM) to install a package called validator, specifically designed for string validation. The installation of the package went smoothly u ...

The child_process in Node is attempting to utilize /usr/bin/zsh, but unfortunately, it is unable to do so because

Recently, I've been encountering issues with several npm commands failing, accompanied by an error message that looks like this: npm ERR! code ELIFECYCLE npm ERR! syscall spawn /usr/bin/zsh npm ERR! file /usr/bin/zsh npm ERR! path /usr/bin/zsh npm ER ...

What is the best way to iterate through these arrays to retrieve just the orderTotal values?

How can I iterate through this array and calculate the total order amount within each Item object? (0) OrderTotal $100 (1) OrderTotal $220 var sum = 320; store the combined OrderTotal values in a variable I aim to obtain the total sum of all order tot ...

Ensuring contact form accuracy using jQuery and PHP

Can't seem to figure out why I am always getting false from the PHP file even though my contact form validation with jQuery and PHP is working fine. Let me explain with my code: Here is the HTML: <form method='post'> <label& ...

Should URL parameters be avoided as a method for retrieving data with React Router in a React application?

Within my application, there exists a main page labeled Home that contains a subpage named Posts. The routing structure is as follows: <Route path='/' element={<Home />} /> <Route path='/posts/popular' element={<Post ...

Getting state values from a custom component to another parent component can be achieved by lifting the state up

In my project, I have two classes both extending React.Component. One of these classes is a custom component that is built upon another custom component called React Places Autocomplete. If you want to see how it looks, check out this picture. Here is the ...

What is the best approach for creating a test that can simulate and manage errors during JSON parsing in a Node.js

My approach to testing involves retrieving JSON data from a file and parsing it in my test.js file. The code snippet below demonstrates how I achieve this: var data; before(function(done) { data = JSON.parse(fs.readFileSync(process.cwd() + '/p ...

How can I change the color of a cube in Three.js?

I'm currently working on developing a basic 3D game using three.js. My goal is to create colored cubes, but I'm encountering an issue where all the cubes are displaying the same color. My cube creation code looks like this: var geometry = new ...

Is it possible to retrieve correctly formatted JSON data from this API?

I need help retrieving data from the API located at . When I access the API directly, it returns an array wrapped in <pre></pre> tags, rather than in JSON format. I would like to use an AJAX call to retrieve this data instead of using PHP. Is t ...

What sets apart express.Router() from using multiple express() objects?

When utilizing the latest express 4 router, it becomes possible to organize various route paths into separate files like the following example: // Inside cars.js const router = express.Router(); router.get('/brands', function(req, res) { ... } ...

Leveraging union types in Mongoose and typescript: Accessing data from a populated field with multiple value options

In my codebase, I have the following models: CoupleModel.ts import mongoose, { Model, Schema } from 'mongoose'; import { CoupleType } from '../types/coupleTypes'; const coupleSchema = new Schema( { user1: { t ...

The art of toggling input values with Angular JS

I have a simple application where users input string values into two fields and the text is incorporated into a sentence. I am looking to add a button that, when clicked, will switch the values in the fields. HTML <body> <div ng-app="myApp" ng ...

Tips on accessing InnerText with VUEJS

I'm struggling with displaying the innerText generated by my generatePseudonym() function in a modal dialog. To better illustrate, here is a screenshot of what I mean: https://i.sstatic.net/pEl5P.png I am aiming to show the output Anastasia Shah as th ...