How to eliminate quotation marks from a nested array in JavaScript

Is there a way to eliminate double quotes from nested array information?

["[a,b,c],[b,c,d],[e,f,g]"]

Transforming it into this array:

[[a,b,c],[b,c,d],[e,f,g]]

through the utilization of javascript

Answer №1

Valid values for variables such as a, b, c, are essential for making sense of the code and ensuring its execution.

An approach to achieve this is by creating a valid JSON string and then parsing it:

var arr = ["[1,2,3],[4,5,6],[7,8,9]"];
var json = "{ \"x\" : [" + arr[0] + "] }";
console.log(json);
var res = JSON.parse(json);
console.log(res.x);
console.log(res.x[0]);
console.log(res.x[1]);
console.log(res.x[2]);

Another method involves using eval():

var arr = ["[1,2,3],[4,5,6],[7,8,9]"];
var res = eval("[" + arr[0] + "]");
console.log(res);
console.log(res[0]);
console.log(res[1]);
console.log(res[2]);

Important Note - Be cautious when using eval() as it can execute any JavaScript code provided, unlike JSON.parse() which is limited to static object data only.


Update - If utilizing the literal variables like a,b,c, they must be predefined in the program's scope. In this case, you can only utilize eval() since it executes within the program's scope whereas JSON.parse() does not.

For instance:

var a = 1,
  b = "hello",
  c = new Date(),
  d = ["p", "q", "r"],
  e = 5,
  f = new Object(),
  g = 7;
var arr = ["[a,b,c],[b,c,d],[e,f,g]"];
var res = eval("[" + arr[0] + "]");
console.log(res);
console.log(res[0]);
console.log(res[1]);
console.log(res[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

Ordering in D3 Code

I'm struggling with understanding the correct structure for writing D3 code. For example: In the code snippet below, I noticed that if I place the 3rd section (Chart Title) of the code after creating the svg element, the title text doesn't displ ...

Toggle classes on button click

<div class='fixed_button homes hidden'> <a class='btn btn-primary homes'>Continue &rarr;</a> </div> Using jQuery Library $(".homes").on('click', function(){ $("choose_style").addClass(&apo ...

The AJAX server call is still experiencing a timeout issue despite having already implemented a timeout

My server ajax call keeps timing out even though the server responds back within a reasonable timeframe. If the server responds within 2-4 minutes, the ajax call goes into success. However, if the server takes longer than 4 minutes to respond, the ajax ca ...

Encountering sporadic EACCES issues while executing selenium tests in the AVA framework

Encountering errors on Windows 10 1809 while using Chrome for testing purposes. Error message 1 Frequency: Occurs approximately every 50th driver instantiation. [...]project\node_modules\selenium-webdriver\net\portprober.js:159 ...

Choosing a button value from a form in Selenium: Best practices

I am looking to streamline the process of registering for classes. The snippet of HTML code on the page appears as follows: <form id="SearchClasses" name="selectedStatusForm" action="/more/SearchClasses.action" method=&quo ...

Presentation Slider (HTML, CSS, JavaScript)

Embarking on my journey of creating webpages, I am eager to replicate the Windows 10 start UI and its browser animations. However, my lack of JavaScript knowledge presents a challenge. Any help in reviewing my code for potential issues would be greatly app ...

What is the specific design pattern that jQuery implements for its get/set methods?

Is there a specific term or pattern that is used by jQuery for its unique style of get and set methods? This pertains to the behavior of the method which changes based on whether an argument is provided or not. For instance: $('#my-element').te ...

Tips for adding new items to a Masonry Image List using React MUI

As I experiment with utilizing the React MUI Masonry Image List alongside the infinite scroll, I've found that they complement each other quite well. However, a challenge arises when appending new images to the Masonry image list. While I can success ...

Error: ng-messages syntax issue with the field parameter

Encountering the following error: Syntax Error: Token '{' invalid key at column 2 of the expression [{{field}}.$error] starting at [{field}}.$error]. when attempting to execute the code below (form-field.html) <div class='row form-grou ...

Is there a way to automatically redirect my page after clicking the submit button?

I'm having trouble with the code below. I want it to redirect to NHGSignin.php if 'new horizon gurukul' is entered. When I click the Next button, it's supposed to take me there but it's not working as expected. Can anyone help me f ...

Find the item that has a specific value in its sub-property

Information Models: public class Header{ public int Identifier; public int value; public bool anotherValue; public List<Trailer> trailers; } public class Trailer{ public int ID; public Language MyLanguage; public string ...

Implementing a custom body class in AngularJS when utilizing partials

Looking for some help with AngularJS. I have an index.html file, along with controllers and partials. The <body> tag is located in the index.html. I am trying to set the class for the body using my controller. After adding a value to $scope.body_c ...

Determine the hour difference between two provided dates by utilizing the date-fns library

My API returns a "datePublished" timestamp like this: "2019-11-14T14:54:00.0000000Z". I am attempting to calculate the difference in hours between this timestamp and the current time using date.now() or new Date(). I am utilizing the date-fns v2 library fo ...

VueX threw an error stating that it cannot read property 'getters' because it is undefined in Nuxt.js

Just starting out with Vuejs and Nuxt.js. I recently set up a Nuxt project but encountered an error when trying to run it: https://i.sstatic.net/ROtOs.png Any assistance would be greatly appreciated. Thank you. ...

Inject "incorrect" information using jQuery

I am dealing with the following constellation: <dl> <dt>Content</dt> <dd>123</dd> <dt>Content</dt> <dd>123</dd> <dt>Content</dt> <dd>123</dd> </dt> ...

AngularJS Splice Function Used to Remove Selected Items from List

I previously inquired about a method to remove items from the Grid and received a solution involving the Filter method. However, I am specifically looking for a way to remove items using the Splice Function instead. You can find my original question here: ...

How to seamlessly integrate Redux into your React project using create-react-app?

Is it correct to pass a reducer as props when using a rootreducer? This is the content of my rootReducer.js file: import { combineReducers } from 'redux'; import simpleReducer from './simpleReducer'; import messageReducer from '. ...

What is the most effective method in Vue.js for transitioning elements without the need to use v-for and v-if at the

Utilizing v-for to generate multiple <p> elements, each one animating in within a Vue <transition> component if the v-if condition is met. Below is the code snippet: <transition name="fade"> <p v-for="(quote, idx) in game.quot ...

Parsing a multidimensional JSON array in Java: A step-by-step guide

I have a JSON array object with two dimensions as shown below {"enrollment_data":{"status":"Active","notes":"None","id":"983761"}} To extract the status, notes, and id from the above JSON array object, I have written the following code: JSONParser parse ...

"Steps for implementing a multiselect feature with checkboxes, including the ability to check all and uncheck all, in a React application

After creating a custom component for selecting multiple options and adding a check all feature, the challenge arises when needing an uncheck option. Solution? Implementing an uncheck all feature alongside the select all functionality, but how to modify th ...