Transform a String into an Array object

There is a string that resembles the following pattern:

var stringArray = "[[1,2,3,4],[5,6,7,8]]"

The objective is to use Javascript to convert it to the following format:

var actualArray = [[1,2,3,4],[5,6,7,8]]

What would be the method to accomplish this task?

Answer №1

Your data is formatted in JSON. To parse it, you can utilize any JSON parsing tool or library. For instance, you can use JSON.parse(stringArray) (source).

Below is an example that demonstrates the use of JSON.parse:

var stringArray = "[[1,2,3,4],[5,6,7,8]]";
var parsedArray = JSON.parse(stringArray);

$('#first').html(parsedArray[0].toString());
$('#second').html(parsedArray[1].toString());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
First element: <span id="first"></span><br>
Second element: <span id="second"></span>


Another approach is using the eval function (guide), but it is recommended to avoid this method whenever possible due to security risks and decreased performance. More information on that can be found here.

Nevertheless, here is an example using the eval method:

var stringArray =  "[[1,2,3,4],[5,6,7,8]]";
var parsedArray = eval(stringArray);

$('#first').html(parsedArray[0].toString());
$('#second').html(parsedArray[1].toString());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
First element: <span id="first"></span><br>
Second element: <span id="second"></span>

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

What is the best way to eliminate query parameters in NextJS?

My URL is too long with multiple queries, such as /projects/1/&category=Branding&title=Mobile+App&about=Lorem+ipsum+Lorem+. I just want to simplify it to /projects/1/mobile-app. I've been struggling to fix this for a week. While I found so ...

Vue.js does not support the usage of external JSON files directly within HTML documents

I'm encountering issues fetching data from an external JSON file for a specific variable. I suspect that the problem lies in using Vue.js within the HTML, as it seems to be having trouble interpreting my code correctly.:joy: jsfiddle Additionally, I ...

fetching JSON information from PHP script in an Android mobile app

As a novice in android app development, I recently attempted to connect my application to a server to retrieve data from MySQL. My initial focus was on creating the login functionality, but encountered challenges with reading JSON data using my code. Here ...

Obtain serialized information from php using ajax

I am currently working with a php script that returns serialized data. I am trying to retrieve this data using the $.ajax() method from jQuery 1.7. You can find an example here. $.ajax({ url: 'http://input.name/get.php?do=lookup' + '&am ...

Does this Spread Operator Usage Check Out?

Upon reviewing Angular's API documentation, I came across the declaration for the clone() method in HttpRequest as follows: clone(update: { headers?: HttpHeaders; reportProgress?: boolean; params?: HttpParams; responseType?: "arraybuffer" ...

Utilizing Angular to efficiently download and showcase PDF files

Presently utilizing https://github.com/stranger82/angular-utf8-base64 as well as https://github.com/eligrey/FileSaver.js/ for the purpose of decoding a base64 encoded PDF file that I am fetching from a rest API. It successfully decodes and downloads, ...

``How can I lock the top row of an HTML table containing input fields in place while

Below is the table structure: <table> <tr> <th>row1</th> <th><input type="text"></th> <th><input type="text"></th> <th><input type="text"></th& ...

Triggering a JQuery Toggle Button

This is the code I'm currently working with: $('.access a').toggle(function() { $('link').attr('href', 'styles/accessstyles.css'); $('body').css('font-size', '16px'); }, fu ...

Utilizing the Current URL from the address bar as a variable to link within the same page

My goal is to: Extract the current URL address from the browser bar, which will have a format like this: http://example.com/test/index.html?&dv1=1023faf2ee37cbbfa441eca0e1a36c Retrieve the lengthy ID number located at the end of the URL 1023faf2ee37c ...

Retrieve information stored within an object's properties

Possible Duplicate: Accessing a JavaScript Object Literal's Value within the Same Object Let's take a closer look at this JavaScript object var settings = { user:"someuser", password:"password", country:"Country", birthplace:countr ...

How to sort data in AngularJS by clicking on a column to change the order from ascending to

The code view below is what I am currently working with: <tr ng-repeat="c in clients | orderBy:'code'"> <td>{{c.firstname}} {{c.lastname}}</td> <td>{{c.telephone}}</td> <td>{{c.location}}</td> ...

Aligning text vertically to the top with material UI and the TextField component

Seeking guidance on adjusting vertical alignment of text in <TextField /> const styles = theme => ({ height: { height: '20rem', }, }); class Foo extends React.component { ... <TextField InputProps={{ classes: ...

Utilizing intricate nested loops in Angular.JS for maximum efficiency and functionality

Struggling to work with data looping in Angular.JS, especially when it comes to specific formatting Let's illustrate what I'm aiming for using Java Here's a snippet: int itemCount = 0; for(int i = 0; i < JSON.length(); i = i + 3) { ...

Top method for retrieving extensive query output to template in Flask

I'm facing a challenge in passing a large query, converted to a JSON string from a list of lists containing over 500000 entries, to a template. The method I am currently using has been effective for smaller datasets: return render_template('/dat ...

Tips for styling cells in a certain column of an ng-repeat table

I am currently facing an issue with a table I have created where the last column is overflowing off the page. Despite being just one line of text, it extends beyond the right edge of the page without being visible or scrollable. The table is built using th ...

Tips on revealing concealed information when creating a printable format of an HTML document

I need to find a way to transform an HTML table into a PDF using JavaScript or jQuery. The challenge I'm facing is that the table contains hidden rows in the HTML, and I want these hidden rows to also appear in the generated PDF. Currently, when I co ...

Tips for accessing nested documents from Firebase in React.js

Here is a snippet of code from my React project: import React, { useState } from "react"; import { db } from "../firebase"; import { collection, Firestore, getDocs } from "firebase/firestore"; function Document() { const ...

Alter the color of a single character using JQuery, all while keeping the HTML tags unchanged

I'm currently working on iterating through the DOM using JQuery in order to change the color of every occurrence of the letter m. Here is what I have so far: $(document).ready(function(){ var m = "<span style='color: red;'>m</span& ...

Bug in toFixed causing incorrect results

function calculateTaxAndTotalRent(rent) { var phoneCharges = parseFloat($('#phone_charges').val()); phoneCharges = phoneCharges.toFixed(2); rent = parseFloat(rent); rent = rent.toFixed(2); var tax = parseFloat((rent * 15) / 1 ...

Parsing JSON data retrieved from an aspx file

I recently created an aspx file to act as a JSON result. Response.Clear() Response.ContentType = "application/json; charset=utf-8" On another page from a different domain, I attempted to read the JSON data. However, upon calling the JSON value, I encount ...