The array within the JSON object holds vital information [Typescript]

I have some data stored in an Excel file that I want to import into my database. The first step was exporting the file as a CSV and then parsing it into a JSON object.

fname,lname,phone
Terry,Doe,[123456789]
Jane,Doe,[123456788, 123456787]

Upon converting the CSV to a JSON object, I noticed that the phone numbers were being treated like strings within arrays.

[
 {
   "fname": "Terry",
   "lname": "Doe",
   "phone": "[123456789]",
 },
 {
   "fname": "Jane",
   "lname": "Doe",
   "phone": "[123456788", 123456787]"
 }
]

What I really need is a JavaScript object where I can interact with the data more easily, such as accessing individual elements like:

convertedData[0].phone[0]

Is there a way to achieve this?

Answer №1

Although accessing data[0].phone directly may not work, you can achieve the same result by using data[0]["phone"] instead.

//This section can be customized for your CSV parsing needs - I organized it this way for easy testing.
const rawData = "fname,lname,phone\nTerry,Doe,[123456789]\nJane,Doe,[123456788, 123456787]";
const lines = rawData.split("\n");

const data = [];
const keys = [];
lines[0].split(",").forEach((key) => keys.push(key));
for (let i = 1; i < lines.length; i++) {
    const line = lines[i];
    const parsedLine = {}
    line.split(",").forEach((value, index) => parsedLine[keys[index]] = value);
    data.push(parsedLine);
}

//Test case example
console.log(data[0]["phone"])

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

Selecting JSONB keys in a case-insensitive manner in PostgreSQL (version 9.4 and newer)

Configuration (Using PostgreSQL 9.4+) Imagine a scenario where there is a table called product: create table product ( attributes jsonb ); and it contains the following data: insert into product (attributes) values ('{"Color": "Red"}'), ...

Align Image According to Dimensions of the Browser

I'm looking for a way to dynamically position an image based on the width and height of the browser within an HTML file. I know that adjusting an image's width/height is possible through code like this: <script> ...

What is the most efficient approach to handle the next state after calling setState in react with immer?

Using Typescript, React, and Immer, I have set up a state management system to save profiles with multiple options. My goal is to ensure that the active profile has the correct option data before saving it. const { updateProfileList, getProfile } = useProf ...

Oops! Looks like the table you're trying to reference hasn't been defined yet

Whenever I attempt to create a table using the Google Visualization API, with PHP & MySQL in the background, I encounter this error message. The database connection is established without issues Generating JSON from the PHP array works correctly The JSON ...

Is there a Wordpress floating bar similar to the one seen on 9gag?

After browsing through some posts on stackoverflow, I noticed that my website is not responding as expected. You can check out my site here: To troubleshoot, you can examine the source code and utilize Firebug to inspect the css and javascript being used ...

Identifying the length of a division element following its addition

I'm facing difficulties in detecting the length and index of the dynamically appended div. I have researched extensively and found a solution involving MutationObservers, but I am unsure if it is necessary for this particular issue. Let's focus ...

Persistent change issue with JQuery CSS function

Looking for some help with a button-bar div that I want to display only after the user clicks on a "settings" button. Currently, I have set the button-bar div to have a display:none property in my css file. However, when the settings button is clicked, t ...

Transition smoothly with a fade-in effect as you scroll through the images, and proceed to

My Objectives: Implement a scrolling feature where images transition to the next one based on scroll movement. Create a cycle of images that automatically progress, with the view transitioning to the bottom section once all images are viewed. Currently f ...

How can I transform Json data into XML format with namespaces included?

Here is an example of a json string: "{ "RSS": { "Channel": { "item": [ { "title": "Overlay HD/CC", "guid": "1", "description": "This example shows tooltip overlays for captions and quality.", "j ...

What is the method for retrieving this data using Javascript?

I received this JSON-encoded data: { "error": { "msg":"Concurrent verifications to the same number are not allowed", "code":10 } } and I tried to access the 'msg' value using JavaScript as follows: $("#buttonPhoneSubmit ...

Creating a custom loading page in Next.js 13: A step-by-step guide

Hello, I am currently working on implementing a loading page for my website to enhance the user experience during a longer loading time. I have created a simple functional component that displays a loading message and imported it into my layout.jsx file in ...

What is the best way to convert an object into an array of objects for use in a select search functionality

I am attempting to map key and value pairs into a single array in order to use them as selectsearch options. I have successfully mapped each item individually, but now I need to combine all the data into one array. How can I achieve this? Here is how I am ...

Create a div element that expands to occupy the remaining space of the screen's height

I am trying to adjust the min-height of content2 to be equal to the screen height minus the height of other divs. In the current HTML/CSS setup provided below, the resulting outcome exceeds the screen height. How can I achieve my desired effect? The foote ...

What is the source of this error message "Exceeding maximum characters in string literal"?

Hey everyone! Sorry for the bother, but I'm a bit stumped on this issue. Within my view, I have the following code snippet: <fieldset> <dl> <dt> <label for="FormTypes">Form Type:</label> ...

The error type currently displayed relates to window['angularComponentReference']

Currently, I am attempting to incorporate NgZone into my Angular project: constructor( private fishboneService: FishboneService, private zone: NgZone, ) { window['angularComponentReference'] = { zone: this.zone, componentFn: (val ...

Ways to ascertain whether a user has successfully logged in

Just diving into Angular testing and decided to test out the checkLogin function within my application. import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import {AuthenticationService} from &qu ...

Incorporate a redirect function following an alert using jQuery, AJAX,

Does anyone know how to implement a redirect after displaying an alert message once a form is submitted? $.ajax({ type: "post", data: person, async:false, url: 'https://webapp.example.c ...

Utilizing Smart Table for Data Binding with JSON Dataset

I need help binding a JSON file to a smart table. How can I use the loop function for iteration? The design of the smart table is displaying, but the data from the JSON file is not binding. Here is the JSON file: [ { "year": 2013, "id ...

In Python, bring in a CSV file that is tab-delimited and remove any newline characters and commas from the

For the past couple of days, I've been working on a Python script to process CSV files. It's almost there, but I keep encountering this error: File "C:\Python34\lib\csv.py", line 149, in _dict_to_list + ", ".join([repr(x) for ...

How can I switch the values of two select components in React js when clicked?

I am working on a project where I have two select components positioned on the right and left side respectively, each with different values - A on the right side and B on the left side. Now, in response to a button click event, I need to swap component A t ...