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?
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'
– Felipe G. Santos
@Felipeg.Santos gives an example of how you would use it
final
. In the question you gave the exampleobj[0[2]] => cinza
and that’s what my answer does. But it gives an example that I can adapt the answer to.– Sergio
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
– Felipe G. Santos
@Felipeg.Santos
final[1][2]
, you have to use[]
followed and not one within another– Sergio