Encountered issue while converting half of the string array to JSON using JavaScript

I encountered an issue with the code below while trying to convert an array into JSON. Here is my code:

<html>

<head>
</head>

<body style="text-align:center;" id="body">
  <p id="GFG_UP1" style="font-size: 16px;">

  </p>
  <p id="GFG_UP2" style="font-size: 16px;">
  </p>
  <button onclick="gfg_Run()">
    Convert
  </button>
  <p id="GFG_DOWN1" style="color:red;
    font-size: 20px; font-weight: bold;">
  </p>
  <p id="GFG_DOWN2" style="color:red;
    font-size: 20px; font-weight: bold;">
  </p>
  <script>
    var el_up1 = document.getElementById("GFG_UP1");
    var el_up2 = document.getElementById("GFG_UP2");
    var el_down1 = document.getElementById("GFG_DOWN1");
    var el_down2 = document.getElementById("GFG_DOWN2");
    var array1 = [34, 24, 31, 48];
    var array2 = [23, 43, 65, 52];
    var numberArray1 = [];
    var numberArray2 = [];
    for (i = 0; i < array1.length; i++) {
      numberArray1[i] = "number" + i + ':' + array1[i];
    }
    el_up1.innerHTML = "Array = [" + array1 + "]";;
    function gfg_Run() {
      el_down2.innerHTML =
        JSON.stringify(Object.assign(numberArray1));
    }

    for (i = 0; i < array2.length; i++) {
      numberArray2[i] = "number" + i + ':' + array2[i];
    }
    el_up2.innerHTML = "Array = [" + array2 + "]";;
    function gfg_Run() {
      el_down2.innerHTML =
        JSON.stringify(Object.assign(numberArray2));
    }
  </script>
</body>

</html>

The current output is:

["number0:23","number1:43","number2:65","number3:52"]

However, both arrays are not being converted as expected.

It should output:

["number0:34","number1:24","number2:31","number3:48"]
["number0:23","number1:43","number2:65","number3:52"]

Answer №1

<html>
<head>
</head>
<body style = "text-align:center;" id = "centered">
<p id = "Title1" style = "font-size: 16px;">

</p>
<p id = "Title2" style = "font-size: 16px;">
</p>
<button onclick = "runFunction()">
Process
</button>
<p id = "Result1" style = "color:red; font-size: 20px; font-weight: bold;">
</p>
<p id = "Result2" style = "color:red; font-size: 20px; font-weight: bold;">
</p>
<script>
var el_title1 = document.getElementById("Title1");
var el_title2 = document.getElementById("Title2");
var el_result1 = document.getElementById("Result1");
var el_result2 = document.getElementById("Result2");
var firstArray = [34, 24, 31, 48];
var secondArray = [23, 43 ,65 ,52];
var numArray1 = [];
var numArray2 = [];
for (i = 0; i < firstArray.length; i++)
{
numArray1[i] = "Phone" + i + ':'+firstArray[i];
}
el_title1.innerHTML = "Array = [" +firstArray+"]";

for (i = 0 ; i < secondArray.length; i++)
{
numArray2[i] = "Phone" + i + ':'+secondArray[i];
}
el_title2.innerHTML = "Array = [" +secondArray+"]";
function runFunction(){
el_result1.innerHTML =
JSON.stringify(Object.assign(numArray1));
el_result2.innerHTML =
JSON.stringify(Object.assign(numArray2));
}
</script>
</body>
</html>

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 world of Vue.js object mapping

I currently have the following object: data: () => ({ customer: { item: { name: undefined }} }) This object is being used in the template as follows: <v-number separator="." decimal="2" ...

Breaking up an array into smaller chunks with a slight twist

Here's a straightforward question. I have an array, like this: let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], maxChunkLength = 3; I am looking to divide this array into multiple arrays as follows: [[1, 2, 3], [3, 4, 5], [5, 6, 7], [7, 8, 9], [9, ...

Set up an event listener for when geolocation permission is approved

My Setup: I've written some basic code snippet below: const onSuccess = () => { console.log('success'); } const onError = () => { console.log('error'); } navigator.geolocation.getCurrentPosition(onSuccess, onError) ...

Exploring the method to find all corresponding keys within deeply nested objects

Within my 'const', I have an array filled with objects. Each object contains a key called 'image' which holds the value for 'url' as illustrated below. const images =[ { "image": { "url& ...

Troubleshooting problem with JSON decoding in PHP and json_encode

Encountering an issue when parsing JSON received from a PHP backend. In my PHP code, I have an array that I send using json_encode: $result[] = (object) array('src' => "{$mergedFile}", 'thumb_src' => "{$thumb_file}"); echo json_e ...

Access a designated tab using cbpFWTabs

I am currently using the cbpFWTabs plugin from Tympanus for my tabs (http://tympanus.net/Development/TabStylesInspiration/). However, I am struggling to open a specific tab upon page load. I have attempted to create a show method within the page script, bu ...

Prevent deletion of already uploaded images in Blueimp by disabling the delete button

After using the blueimp upload script to upload files, I noticed that the file information is saved in a data table along with the upload timestamp. However, when I go to edit the form, the files reappear. The simple task I want to achieve is disabling th ...

Navigate forward to the next available input in a grid by using the tab key

My goal is to improve form entry efficiency by using the tab key to focus on the next empty input field within a grid component. If an input field already has a value, it will be skipped. For example, if the cursor is in input field 2 and field 3 is filled ...

Using JavaScript functions to modify the style of the DOM

Is there a way to change the style of a dom element using JavaScript when only the element id and style value are passed as parameters, without passing the actual style parameter itself? For example, is it possible to use the id "first" and set the color ...

Grid layout with columns of equal width in Bootstrap

I'm currently working on creating a dashboard with Angular and Bootstrap 4. I've utilized the equal-width columns from https://getbootstrap.com/docs/4.0/layout/grid and it's functioning well. However, I'm facing an issue where if the lo ...

Steps to stop mat-spinner upon receiving Job Success/Failure Notification from the backend

I have a task that runs asynchronously and takes a long time to complete. When the task starts, I display a mat-spinner with a timeout set at 60000 milliseconds. However, we now have a notification service that provides updates on the job status. I would l ...

Navigating Angular's Credit Card Input Functionality

I am looking to limit the input capacity to 16 numbers and add a space between each set of 4 numbers. After conducting an extensive search for a credit card input that allows users to enter 16 digits with a " - " or space in between, all results were for ...

Learning how to interpret and implement this particular syntax within JavaScript Redux Middleware can be a valuable skill

Currently, I am diving into the world of redux middleware by referring to this informative article: http://redux.js.org/docs/advanced/Middleware.html The code snippet presented below serves as an illustration of how a logging middleware works. const log ...

The JADE form submission is not being captured even though the route is present

I am currently utilizing JADE, node.js, and express to develop a table for selecting specific data. This entire process is taking place on localhost. The /climateParamSelect route functions properly and correctly displays the desired content, including URL ...

Libraries that automatically suggest options for integrating objects described by JSON schema

We are currently developing a platform with an email templating feature. Users can insert objects and variables into their emails using json-schema. Although we are not the first ones to work on this, our research has not turned up many libraries that cou ...

Keep moving the box back and forth by pressing the left and right buttons continuously

Looking to continuously move the .popup class left and right by clicking buttons for left and right movement. Here is the js fiddle link for reference. This is the HTML code structure: <button class="right">Right</button> <button class="l ...

jQuery issue: Inability of "Read More" span to reappear after clicking "Read Less"

Currently in the process of creating a portfolio website that showcases project descriptions with an excerpt, revealing full details upon clicking "Read More." My experience with jQuery is limited, but I managed to implement functionality where clicking "R ...

Angular calls a factory method from within its own factory

When working in my controller, I encountered a situation where I needed to call a factory function recursively. Previously, the code worked fine as simple JavaScript functions not defined within the factory itself, but I wanted to improve isolation. Here ...

Why won't the display: block CSS style apply to my div element?

Take a look at my code: https://jsfiddle.net/r62p4209/ I created a search bar with company brand name and some buttons on the right, positioned in the center. My aim is for the search bar (from "search by:" to the "Go!" button) to move onto the next lin ...

Is there a way to verify an email address and transfer form data to a different HTML page for printing?

How do I troubleshoot email validity checking issues in my form? It works fine when no characters are entered, but fails when characters are inputted. What could be causing this problem? Additionally, I want to open a new HTML sub-file after form submissi ...