how to index an object numerically in Node.js?

Asked

Viewed 57 times

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 that 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’t access the properties using numeric index. there’s a better way to do that?

1 answer

0

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

Something like that:

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]}

  • his reply helped me a lot but the output I got was this // ["animal",["white","black","gray"],"insect",["white","black"]] which prevents me from using "gray" as a position of the 'animal" array'

  • @Felipeg.Santos gives an example of how you would use it final. In the question you gave the example obj[0[2]] => cinza and that’s what my answer does. But it gives an example that I can adapt the answer to.

  • its code worked well for me, I can access the positions numerically, but if I print final[1] the answer that should be 'insect' is actually '['white','black','gray']' because this array is not being value for 'animal' key but another key, if I print 'obj[0[2]]' I will only have 'Undefined' as output

  • @Felipeg.Santos final[1][2], you have to use [] followed and not one within another

Browser other questions tagged

You are not signed in. Login or sign up in order to post.