What is the method for transforming a JavaScript array (without an object name) into JSON format (with an object name)?

Currently, I am using an ajax query to read a local csv file and then loading the extracted values into an array.

This is how the string value appears in the csv file:

"Tiger","Architect","800","DRP","5421","VFX"

After loading this string into the array, it looks like this:

0: (6) ["Tiger", "Architect", "800", "DRP", "5421", "VFX"]

Now, my objective is to convert this aforementioned string into a JSON object structured as follows:

{
    "data": [
    {
    "0": "Tiger",
    "1": "Architect",
    "2": "800",
    "3": "DRP",
    "4": "5421",
    "5": "VFX"
    }]
}

With all the values encapsulated within the data object.

I attempted the following code for this purpose:

var arrayToString = JSON.stringify(Object.assign({}, data1)); 
var stringToJsonObject =  JSON.parse(arrayToString); 

The code successfully converts the array into JSON format, but with a length of 6, whereas I require it to be 1

Is there any alternative method to achieve this?

Answer №1

It looks like you're almost finished with everything, just remember to enclose the array in square brackets when creating an object.

const arr = ["Tiger", "Architect", "800", "DRP", "5421", "VFX"];
    
var arrayToString = JSON.stringify(Object.assign({}, [arr])); 
var stringToJsonObject =  JSON.parse (arrayToString) ; 

console.log(stringToJsonObject);

Answer №2

To achieve this task, you can utilize the Object.entries method along with Object.fromEntries.

const arr = ["Tiger", "Architect", "800", "DRP", "5421", "VFX"];

const result = {data: []};

result.data.push(Object.fromEntries(Object.entries(arr)));

console.log(result);

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

Capturing attention within react-bootstrap drop-downs and pop-ups

Currently, I'm focused on enhancing accessibility features and I have a specific goal in mind: to confine the focus within a popover/dropdown whenever it is opened. Working with react-bootstrap, my inquiry revolves around finding out if there's ...

Circular dependency in Typescript/Javascript: Attempting to extend a class with an undefined value will result in an error,

Query Greetings, encountering an issue with the code snippet below: TypeError: Super constructor null of SecondChild is not a constructor at new SecondChild (<anonymous>:8:19) at <anonymous>:49:13 at dn (<anonymous>:16:5449) ...

Is there a way to modify the window's location without having to reload it and without resorting to any sne

Initially, I believed that the hash hack was a necessity, but after observing the recent updates from Facebook, my perspective has shifted. The original hash hack (not certain if this is the correct term) involved changing location.hash to save a state in ...

Unable to trigger AJAX Complete Handler

Upon completing extensive backend work on my web application, I discovered that the GetMeasure Request was taking up to 10 seconds to finalize. To prevent confusion for potential users, I decided to implement an overlay so that they would not be left stari ...

How can I incorporate a personalized SVG path to serve as a cursor on a webpage?

Is there a way to enhance the functionality of binding the 'mousemove' event to a div and moving it around the page while hiding the real cursor? Specifically, can we change the shape of the circle to an SVG path and drag the SVG path around the ...

Using double quotes in strings with JSON and ASP.NET MVC

When returning a string in JSON format via a webform, the escaping of double quotes works correctly and everything functions as expected. However, in MVC, the formatting displays the escaped quotes in \" format, causing the JSON format to be corrupted ...

Is there a way to access and invoke a exposed function of a Vue component within a default slot?

Exploring the realms of a vue playground. The functions interfaceFunction in both ChildA and ChildB are exposed. In App, these functions can be called by obtaining references to the components that expose them. This allows direct function calls from with ...

Utilizing PHP with WordPress: Execute the specified .js file if the link includes the ID "124"

I am currently using WordPress on my local server and I want to set up a redirect after a user submits the contact form through the Contact Form 7 Plugin. I am looking to redirect them to a specific page, but so far, the plugins I have tried have caused th ...

Component with Next.JS Server-Side Rendering

Is it possible to integrate a module into my project that only supports server side rendering? Here is the current project structure: index.js view.js part.js (Class component) Currently, I am able to use the module in the getServerSideProps method in ...

Trouble arises when rendering nested components in React Router 4

My issue lies with implementing React Router 4 while utilizing "nested" routes. The problem arises when one of the top routes renders a component that matches the route, even though I do not want it to be rendered. Let me provide the relevant code snippets ...

Displaying a division when a button is pressed

Despite my best efforts, I can't seem to get the chosen div to show and hide when the button is pressed. <button id="showButton" type="button">Show More</button> <div id="container"> <div id="fourthArticle"> <i ...

Sending data between two elements when a jQuery event is triggered

As a JavaScript beginner, I am facing an issue where I need to push data from an h1 tag to a textarea. My website is built using WooCommerce and when a visitor clicks on a product, a chat box with the product title opens. Currently, I have successfully p ...

Converting a string to a number is not functioning as expected

I am facing a problem with an input shown below. The issue arises when trying to convert the budget numeric property into thousands separators (for example, 1,000). <ion-input [ngModel]="project.budget | thousandsSeparatorPipe" (ngModelChange)="projec ...

Having trouble dynamically displaying the '<' symbol using JavaScript?

Whenever I attempt to show a string with the character '<' in it, the part of the string that comes after the symbol is not displayed. Strangely enough, when I output it to the console, it appears correctly. Take a look at this excerpt showcas ...

Utilize Python to search and substitute text in numerous CSV files

I have approximately 40 CSV files along with a separate file containing 'find' and 'replace' data. The find column holds the values that need to be located, while the replace column stores the text for replacement. Is there a method to ...

Choose information based on the prior choice made

Using the Material UI Stepper, I have a task that involves setting conditions based on the selection of checkboxes. In step one, there are two checkboxes - Individual and Bulk. In step two, there are also two checkboxes - First Screening and Second Screeni ...

Is there a method to incorporate a click event for the confirm button in the ElMessageBox UI element?

When I try to remove data from the table, I need a warning message to appear in the center of the screen first. The delete function is already set up, but I'm struggling to figure out how to implement a confirm button click event with ElMessageBox. I ...

Amazon S3 Landing Page Featuring Contact Form

Although S3 is not a fileserver, it serves as an excellent tool for managing static websites. The majority of my projects are 99% static, making it ideal for this particular project. As an AWS Solutions Architect, I am struggling to find the most straightf ...

What is the best way to insert a button at the end of the last row in the first column and also at the

I am working on a JavaScript project that involves creating a table. My goal is to dynamically add buttons after the last row of the first column and also at the top of the last column. for (var i = 0; i < responseData.length; i++) { fo ...

Tips for replacing the nested array object in JavaScript

I am seeking guidance on how to merge and overwrite the existing object values in a nested array using JavaScript. In the scenario presented below, I want to merge the 'other_obj' with the 'obj' that has an id of "zen", overwriting the ...