What is the best way to generate an array of objects in a dynamic fashion?

I have retrieved an array of objects from a csv file and it looks like the following when printed:

Array[4]
0:Object
    value1:"200"
    value2:"95"
    value3:"6395"
    value4:"2"
1:Object
2:Object
3:Object

The process I used to create this array is as follows:

var strCSV = e.target.result;
var arrCSV = strCSV.match(/[\w .]+(?=,?)/g);
var noOfCols = 4;

// Ignoring the header row
var hdrRow = arrCSV.splice(0, noOfCols);

var data = [];
while (arrCSV.length > 0) {
    var obj = {};
    var row = arrCSV.splice(0, noOfCols)
    for (var i = 0; i < row.length; i++) {
        obj[hdrRow[i]] = row[i].trim();
    }
    data.push(obj)
}

Now if I want to create another array with the same data but different keys, like so:

var tableData = [
        {key1: "", key2: "", key3: "", key4: ""}];

I have attempted various methods to achieve this but haven't been successful. For example, I tried the following approach:

for(var i=0; i<data.length; i++){
    tableData[i]["key1"] = data[i].value1;
}

Creating an empty array thinking that adding elements on the go would work, but it did not. Is there a way to accomplish this without manually copying each element from the original array?

Answer №1

To generate an array of random objects and values, you can use the code snippet provided below. Start by creating an array with a length of 12 followed by defining the object.

const data = Array.from({
    length: 12
}, () => ({
    id: Math.floor(Math.random() * (100 - 1)) + 1,
    name: Math.random().toString(36).substr(2, 10)
}))

console.log(data)

Answer №2

Here is a solution:

for(let index=0; index<data.length; index++){
    console.log(index);
    let newObj = { "property1": data[index].value1, "property2": data[index].value2};
    tableInfo.push(newObj);
}

Answer №3

Generating a fresh item and subsequently adding it to the tableData collection.

for(let j=0; j<data.length; j++){
    console.log(j);
    let brandNewData = { "property1" : data[j].element1 };
    tableData.push(brandNewData);
}

Answer №4

// initialize empty array
let data = [];

// loop through some condition
for (...) {
    // create new object with two keys
    let newObj = { name: "", age: "" };

    // push object to the array
    data.push(newObj);
}

Answer №5

In order to assign a value to tableData[i]["key1"], it is necessary to first insert an object into tableData[i].

for(let index = 0; index < info.length; index++){
    console.log(index);
    tableData[index] = {};
    tableData[index]["key1"] = info[index].value1;
}

An alternative approach is to combine object initialization and property assignment in the same step:

for(let j = 0; j < info.length; j++){
    console.log(j);
    tableData[j] = {key1: info[j].value1};
}

Answer №6

Have you considered assigning the keys directly from your csv headers to your object? This approach would eliminate the need for additional loops and parsing, streamlining the process.

var csvData = `foo,bar,baz\na,b,c\nd,e,f\ng,h,i`;

function parseCsvData(str) {
  let split = str.split("\n");
  let header = split.shift().split(',');
  let result = [];

  split.forEach((line) => {
    let obj = {};
    line.split(',').forEach((el, i) => {
      obj[header[i]] = el;
    })
    result.push(obj);
  });
  return result;
}

console.log(parseCsvData(csvData));

Alternatively, if you have different headers that you want to assign:

let data = `foo,bar,baz\na,b,c\nd,e,f\ng,h,i`;
let customHeaders = ["head1", "head2", "head3"];
function parseCustomCsv(str) {
  let split = str.split("\n");
  split.shift();
  let result = [];

  split.forEach((line) => {
    let obj = {};
    line.split(',').forEach((el, i) => {
      obj[customHeaders[i]] = el;
    })
    result.push(obj);
  });
  return result;
}

console.log(parseCustomCsv(data));

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

AngularJS issue: Form submission does not trigger the controller function

I am currently learning AngularJS and I am experimenting with the sample code below to send my form data to the server. <!doctype html> <html lang=''> <head> <meta charset="utf-8"> <script src="../js/angular.min.v1 ...

Issue with updating required Node.js/Express modules using Chokidar?

After browsing through numerous questions and answers regarding chokidar, I am still struggling with an issue. It would be greatly appreciated if someone could help debug my particular code snippet. The Express node app I am working on is running at local ...

Real-time Calculation and Validation of Input Field Totals Using JQuery with Modulus % Rules

Hello, I need assistance with validating my input fields to accept values that are divisible by certain numbers. The criteria are as follows: inputValue % 10 == 0; inputValue % 20 == 0; inputValue % 50 == 0; inputValue % 100 == 0; inputValue % 200 == 0; ...

Creating a 64-bit array in Java can allow you to store values larger than Integer_max-value. Here's a straightforward way to

I've been attempting to calculate the sum of prime numbers. To speed up the process, I precomputed them in a lengthy array. However, the final two test cases are yielding incorrect results due to overflow issues. The problem arises from the maximum va ...

Prevent another user from accessing a webpage while another user is already active on it using ReactJs

Currently, I am developing a system where multiple users will be logged in simultaneously. However, it is essential to ensure that two individuals cannot access the same user record at the same time. How can I prevent this from happening? For example, if t ...

Encountering a TypeError while pre-rendering a page during the npm run build process

I am currently preloading this page on my Next.js application: const router = useRouter(); if (!router.isFallback && !postData?.slug) { return <p>Hmm... looks like an error</p> } const formatDate = date => { const newDa ...

Is there a way to configure Cordova to utilize Yarn JS instead of NPM when installing plugins?

Updated Question: When adding plugins to my Cordova project, I currently use the command cordova plugin add x, which I believe utilizes npm in the background. Is there a way to switch out npm for Yarn within Cordova? This change would greatly impact cach ...

How should a php associative array be properly initialized?

Creating a sophisticated associative array in php is my next challenge. Before diving into it, I must successfully initialize it. What would be the ideal approach for initialization? Here's how I am initializing it currently: $ComplexAssociativeArra ...

"Is it possible to conditionally render a component depending on the state in

One of the challenges I'm facing is customizing a filter icon from MaterialUI. My goal is to change its color to black when a checkmark is checked, and adjust its position accordingly. Additionally, when a box is checked, it should fill in setFilters. ...

How to send a DOM element's value to an AJAX request using HTML.PagedList parameters

As I delve into learning ajax requests, I find myself questioning if I am on the right track. Currently, I have a page that incorporates pagination, sorting, and searching functionalities. My goal is to implement these features using ajax to avoid reloadin ...

What is the best method for updating the .value property within an AngularJS controller?

I managed to successfully pass a value from one AngularJS module to another using the .value method. Here is an example of it working: var app = angular.module('app', []); app.value('movieTitle', 'The Matrix'); var app1 =ang ...

Securing Objects in Parse with the JavaScript API - Linking Users to their saved entities

When managing entities in Parse, I often need to associate various objects with the user currently logged in. My main concerns are: There is no backend code in place to ensure that the User being passed in is actually the logged-in user. Users could poten ...

Managing 404 errors when loading cached scripts with jQuery

I need to load a JS file using jQuery, but I want the cache to be used if available. Unfortunately, I can't set the global ajax cache setting to true for reasons beyond the scope of this post. This means using the getScript method is not an option. Fo ...

Combining Various Items Retrieved from Fetch Request

I am attempting to merge multiple objects retrieved from an API by grouping them based on their id and values, ensuring that any modifications are only applied to individual objects rather than affecting all of them. Here is my latest approach: const car ...

Why does ASP.NET sometimes set my JavaScript object to null?

There is a <script> in my code that includes the following line: var tbl = document.getElementById("<%= this.tblSelection.ClientID %>"); Despite this, when the script runs, tbl always ends up being set to null. The table has been defined lik ...

Issue with Browsersync functionality in Docker

My Node.js app is facing an issue with Gulp, Browsersync, and Docker. When I run gulp watch locally, everything functions correctly. However, when I utilize docker-compose up, I encounter an error Cannot GET / The Browsersync UI on port 3001 is operat ...

Converting CSV data into a serialized array using PHP

I am faced with an issue involving a CSV file containing 2 columns: id and key. A snippet of the file includes... 26,"test1 test2 test3 " 54,"test34 test52 test673 " 67,"test1 test2a test333 " My current task is to import this file into PHP and transform ...

I have a query related to material-ui 4, specifically the material-ui/pickers component that is reporting an error regarding a non-existent "mask" property

Recently, I upgraded a reactjs project that uses Material-UI (mui) from version 3 to version 4 by following the recommended migration guide. In the process, I also replaced material-ui-pickers 2.2.1 with @material-ui/pickers. However, after the upgrade, t ...

Transferring a JavaScript variable to C# to execute an SQL SELECT query, then sending the returned result back to JavaScript

I am facing an issue while trying to execute code in my Code Behind to query my SQL Server using a JavaScript variable and then return the result as an Integer back to my Javascript. My approach involves running some Javascript code initially to obtain a ...

Button outline appears upon clicking the link and remains until another area of the page

I have always been curious about a particular situation: Imagine you have a one-page website with a navigation menu. When a user clicks on a navigation link, it scrolls to that section of the website. However, after clicking, the navigation link remains v ...