I am having a hard time figuring out how to access a property of my javascript object.
I have a Node JS application that downloads a CSV file from the WHO with covid data and then I loop through each of these entries. Here is how I loop through each of the CSV entries:
fs.createReadStream("data.csv")
.pipe(csv())
.on("data", (data) => {
//process data
})
.on("end", () => {
});
Here is one sample of the output when I run console.log(data)
{
'Name': 'Niger',
'WHO Region': 'Africa',
'Cases - cumulative total': '6203',
'Cases - cumulative total per 100000 population': '25.63',
'Cases - newly reported in last 7 days': '64',
'Cases - newly reported in last 7 days per 100000 population': '0.26',
'Cases - newly reported in last 24 hours': '10',
'Deaths - cumulative total': '205',
'Deaths - cumulative total per 100000 population': '0.85',
'Deaths - newly reported in last 7 days': '1',
'Deaths - newly reported in last 7 days per 100000 population': '0',
'Deaths - newly reported in last 24 hours': '0'
}
If I run typeof data I am getting object.
I would like to access some properties of this object.
If I output data["WHO Region"] I get "Africa". So this works.
However, I am unable to access the name of those object.
console.log(data["Name"]);
console.log(data.hasOwnProperty("Name"));
Outputs respectively undefined and false
Even though the name property is present within the object.
I have also tried to list the keys of the object with Object.keys(data) and here is the result:
[ 'Name', 'WHO Region', 'Cases - cumulative total', ... ]
So apparently the key Name does exist but I can't access it for some reason. Am I missing something there?
You have invisible symbol in the Name property of the object. You can see it if you past result of the console.log in the browser console:
Check your original CSV file and search for this invisible character.
EDIT: This symbol is ZWNBSP (Zero Width No-Break Space) at the start of the file.
The issue is caused by the Byte Order Mark (BOM) at the start of the file, represented by the byte sequence 0xEF,0xBB,0xBF corresponding to the UTF-8 codepoint U+FEFF.
An easy workaround for your code would be to replace this like so:
const results = [];
fs.createReadStream('data.csv')
.pipe(csv())
.on('data', (data) => {
// Replace BOM in key
const key1 = Object.keys(data)[0];
data = { ...data, [key1.replace(/\uFEFF/, '')]: data[key1] };
results.push(data);
})
.on('end', () => {
results.forEach(result => {
console.log(`Name: ${result["Name"]}`);
})
});
or
You could open the file in Nodepad++ and using the Encoding menu change it from UTF-8-BOM to UTF-8 and saving.