I have the following snippet code which, within a loop, creates a JavaScript object where some of the properties maybe undefined:
reader.on('record', function(record) {
let p = record.children;
let player = {};
// below we create a dynamic key using an object literal obj['name'], this allows use to use
// the id as the firebase reference id.
player[p[0].text] = {
id: parseInt(p[0].text, 10) || "",
name: p[1].text || "",
country: p[2].text || ""
};
};
My question therefore; is there a better way for creating this object via a 'Map' for example? If the properties are undefined then do not add them to the object.
Note: This data is being sent to a Firebase DB, so any undefined values throw an error -- my crude (but working) approach is to add them as an empty string.
Here is a sample of the JSON I would like to see (notice country is not missing from the second player):
{
"players" : {
"100001" : {
"id" : 100001,
"name" : "Matt Webb",
"country" : "ENG"
},
"100002" : {
"id" : 100002,
"name" : "Joe Bloggs",
}
}
p
, have another of keys that should match["id", "name", "country"]
and then just make a loop where you do something likeif (p[i]) currentPlayer[keys[i]] = p[i]
- thencurrentPlayer
would only have the properties with values, the rest would be skipped. \$\endgroup\$