Skip to content
Advertisement

How can I fix this for loop to print results inside an Array with Objects?

Rookie here, I have been breaking my head all day trying to figure this one out…

I have tried different approaches trying to figure this out and looking all over this site for some references, but I have come short and hit a roadblock.

This is my code currently:

import fs from 'fs'
import csvjson from 'csvjson'

const path = 'cyberBackgroundChecks/importer/assets/file.csv'

if (path && fs.existsSync(path)) {
    let file = fs.readFileSync(path);
    file = file.toString()
    const json = csvjson.toObject(file)

    let dataObject = {}

    for (let i = 0; i < json.length; i++) {
        if (json.length > 0) {
            dataObject['index'] = i
            dataObject['name'] = json[i]['OWNER 1 FIRST NAME'] ? json[i]['OWNER 1 FIRST NAME'] : json[i]['OWNER 1 LAST NAME']
            dataObject['streetAddress'] = json[i]['SITUS STREET ADDRESS']
            dataObject['city'] = json[i]['SITUS CITY']
            dataObject['state'] = json[i]['SITUS STATE']
        }
        console.log(dataObject)
    }
} else {
    console.log('The file does not exist');
}

I’m trying to get it to console log like this:

[
  {
    index: 0,
    name: 'Betsy',
    streetAddress: '1452 20th Ave',
    city: 'Seattle',
    state: 'WA'
  },
  {
    index: 1,
    name: 'Donald',
    streetAddress: '2702 NW 67th St',
    city: 'Seattle',
    state: 'WA'
  }
]

However, with my code, I can only get it to console log like this:

{
  index: 0,
  name: 'Betsy',
  streetAddress: '1452 20th Ave',
  city: 'Seattle',
  state: 'WA'
}
{
  index: 1,
  name: 'Donald',
  streetAddress: '2702 NW 67th St',
  city: 'Seattle',
  state: 'WA'
}

Advertisement

Answer

Currently, you are printing data object 2 times inside the for loop. What you want to do is to create an array, add 2 data objects in the array and then print the array.

const dataObjectArr = [];
for (let i = 0; i < json.length; i++) {
    let dataObject = {};
    dataObject['index'] = i;
    dataObject['name'] = json[i]['OWNER 1 FIRST NAME'] ? json[i]['OWNER 1 FIRST NAME'] : json[i]['OWNER 1 LAST NAME'];
    dataObject['streetAddress'] = json[i]['SITUS STREET ADDRESS'];
    dataObject['city'] = json[i]['SITUS CITY'];
    dataObject['state'] = json[i]['SITUS STATE'];
    dataObjectArr.push(dataObject);
}
console.log(dataObjectArr);

I removed this statement if (json.length > 0) because this will always be true as the loop already checks json.length.

A good practice is to end a line in the javascript code with semicolon.

Advertisement