What is the process for transforming an array into an array object using javascript?

Here is a situation where I need to upload a text file that contains data in the following format:

a1,b1,,c1,d1,
a2,b2,,c2,d2, 

After reading and splitting the data with ("\n"), it results in an array like this:

array=[array[0]:[a1,b1,,c1,d1]
       array[1]:[a2,b2,,c2,d2]]

I am looking for a way to populate the above array into my array object.

For example, the desired output would be:

newarray=[[name="a1",age:"b2",address="",contact="c1",gender="d1"],
           [name="a2",age:"b2",address="",contact="c2",gender="d2"]]

Answer №1

One approach to tackle the fixed position of attributes in an array is to create a function that assigns values based on their predetermined positions. Here's an example:

var data = "John,30,123 Main St.,123-456-7890,Male\nJane,25,456 Park Ave.,987-654-3210,Female";
var records = parseData(data);
console.log(records);

function parseData(dataString){
  var recordList = [];
  var lines = dataString.split("\n");
  for(var i=0;i<lines.length;i++){
    var valueArray = lines[i].split(",");
    recordList.push(mapToRecord(valueArray));
  }
  return recordList;
}

function mapToRecord(array){
  return {
    name: array[0],
    age:array[1],
    address: array[2],
    contact: array[3],
    gender:array[4]
  };
}

Answer №2

def convert_list_to_dict(lst):
    new_dict = {}
    for item in lst:
        key = item[0]
        value = item[1]
        new_dict[key] = value
    return new_dict

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

How to update a value within a deeply nested array in MongoDB and then sort the data

In my document, I have a list of timestamps that are sorted by time: { _id: '1', timestamps: [ { id: '589b32cf-28b3-4a25-8fd1-5e4f86682199', time: '2022-04-13T19:00:00.122Z' }, { id: '781 ...

Invalid template detected within the Kendo dropdown component

I am trying to create a template that will only be displayed if the data value is "Low". This is how I have set up my template column: template: '# if( data=="Low" ){#<span><i class="fa fa-square blue"></i> <span># } ' U ...

I am encountering an issue where the POST data is not being successfully sent using XMLHttpRequest unless I include

I have a unique website where users can input a cost code, which is then submitted and POSTed to a page called 'process-cost-code.php'. This page performs basic validation checks and saves the information to a database if everything is correct. T ...

Design a captivating Profile Picture form using HTML and CSS styling

In my form, I am looking to include a user's Profile picture which should be displayed in either a circular or rectangular shape. Initially, the image area will show a black background or a placeholder image. When the user clicks on this area, they sh ...

Attempting to add color to a cube using Three.js

Attempting to apply three different colors to a cube in three.js, it appears that there may be a limit on the number of THREE.DirectionalLight objects that can be added to a scene. The lack of mention of such a limit in the documentation has raised questio ...

leveraging express.js middleware alongside jwt and express-jwt for secured authentication in express framework

I am encountering an issue while using the express-jwt to create a custom middleware. The error message persists as follows: app.use(expressJwt({ secret: SECRET, algorithms: ['HS256']}).unless({path: ['/login', '/']})); ...

Unfortunately, CSS3 PIE is not compatible with border-radius and box-shadow properties

I created a basic HTML/CSS code for testing purposes, but I'm having trouble getting the library to function properly. I've placed the .htc, .php and .js files in the same directory as index.html, but it just won't work. Check out the code ...

Manage the Cancel button functionality in Safari/Chrome when dealing with the Open in App Store pop up

Is there a way to manage the Cancel button on the Open in App prompt when redirected from Safari/Chrome to the AppStore? The situation is as follows: A user is prompted to download the app via a browser link. Upon clicking the link, it determines whether ...

The value is undefined until a new Resource object is pushed with the item

I've encountered an issue while testing a factory and I can't seem to find anyone else with the same problem. Can someone help me figure out what's causing this strange error? TypeError: 'undefined' is not a function (evaluating & ...

Place the image on the canvas

I currently have a canvas where I am able to add text layers and images from flickr. My goal is to enable users to upload an image to the canvas using the html input. For uploading images from flickr, I am using this code: $(".search form.image-search"). ...

Issue with displaying leaflet.js map on Node.js using Express and Jade template

My goal is to display a map on a webpage using a Jade template. The template code is as follows: html head script(src='http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.js') link(rel='stylesheet', href='http://cdn.leafletjs.c ...

I need assistance with retrieving the value in a password field using JavaScript. I've been stuck on this issue all morning and would greatly appreciate any

Currently utilizing document.getElementById("password").value for retrieving the input value of the password field. Seeking assistance! Additionally, the form contains an action="authenticate_signup.php" Encountering an issue where the password field va ...

The selector-triggered JQuery event being invoked by my script

Facing an issue while trying to invoke my jQuery event. I am working with 2 jQuery events: $element.on('click', function (e) { ... }); $element.on('click', '.toggle', function (e) { ... }); My question is how can I trigge ...

Demystifying Iron Ajax: Unraveling the process of parsing an array of JSON objects from a successful

When making an AJAX call to the server, I receive a response in the form of an array of objects as JSON. [{"dms":[{"serialNo":"EG0022","status":"running","firmwareStatus":"ok","latitude":37.8688,"longitude":-144.2093,"toolType":1},{"serialNo":"EG0022","st ...

Is there a way to access the value variable from a JavaScript file located in the javascript folder and bring it to the routes/index.js file in a Node.js and Express application?

I'm currently working on transferring the input value from an HTML search box to the index route file in Node.js using Express. I have successfully retrieved the value from the search box in the javascript/javascript.js file, and now my objective is t ...

Tips for creating a unique scroll page arrow button with adjustable thickness?

Seeking guidance on how to adjust the thickness of the arrow used as a scroll button on my website. I am aiming for a similar look to the arrow on this particular website: example of arrow https://i.sstatic.net/wO5br.png To view my code, please visit: Cod ...

Guide to sending properties to reducer in React with Redux

I've been grappling with the complexities of react-redux for hours. I'm aiming to display an <Alert /> to the user when the value of isVisible is true. However, I'm still struggling to grasp the architecture of redux. Despite my effort ...

Is it possible to reveal a concealed element or modify the functionality of a hyperlink?

I have a link in the navigation that includes an animated icon of a + turning into an x. When the icon is in the x state, I want users to be able to close it by clicking on the icon or text. However, I am unsure of the best way to approach this. One op ...

How to achieve the wrapping functionality in ReactJS that is similar to

Is there a ReactJS equivalent to jQuery's wrap method? I want to wrap menuContents with the following element: <ul className="nav nav-pills nav-stacked"></ul> The contents of menuContents are generated like this: let menuContents = thi ...

Tips for transferring properties from one React component to another React component

I need to figure out how to activate a button in a modal when text is entered into an input field. The form is part of a different class and is utilized within a parent class. How can I pass an onChange method to my form component? Check out the code for ...