how to index an object numerically in Node.js?

0

I'm getting a .csv like this:

animal, branco
animal, preto
inseto, branco
inseto, preto
animal, cinza

I want to be able to use this mass of data this way:

// obj = { animal : [branco, preto, cinza] , inseto:[branco, preto]}

BUT that I can access this information with numeric index (something like this)

// obj[0] => animal : [branco, preto, cinza]
// obj[1] => inseto :[branco, preto]
// obj[0[2]] => cinza
// obj[1[0]] => branco

I'm currently using a forEach like this:

const csvFile = fs.readFileSync(__dirname + '/in/classification.csv', 'utf8');
let data = csvFile.split('\n');
let final = {};
csv.forEach(function (row) {
    row = row.split(',');
    if (!final[row[0]]) {
        final[row[0]] = [];
    }
    final[row[0]].push(row[1]);
});

// output: { animal : [branco, preto, cinza] , inseto:[branco, preto]}

but I can not access the properties using numeric index. is there a better way to do this?

    
asked by anonymous 01.12.2017 / 03:20

1 answer

0

To access with numeric index you must use arrays. And inside the array you can have objects.

Something like this:

const csvFile = '
animal, branco
animal, preto
inseto, branco
inseto, preto
animal, cinza
';
//const csvFile = fs.readFileSync(__dirname + '/in/classification.csv', 'utf8');

const data = csvFile.split('\n');
const types = {};
data.forEach(function(row) {
  if (!row.trim()) return; // empty line;
  const [type, value] = row.split(',').map(s => s.trim());
  if (!types[type]) {
    types[type] = [];
  }
  types[type].push(value);
});
const final = Object.keys(types).reduce((arr, type) => {
  return arr.concat(
    [type, types[type]]
  );
}, []);

console.log(JSON.stringify(final));

// output: { animal : [branco, preto, cinza] , inseto:[branco, preto]}
    
01.12.2017 / 09:17