I have an array of object :
let data = [
{ "date" : "17/03/2022", "count" : 2, "[email protected]" : 2 },
{
"date" : "17/05/2022",
"count" : 2,
"[email protected]" : 1,
"[email protected]" : 1
},
{ "date" : "17/07/2022", "count" : 7, "[email protected]" : 7 },
];
I would like to remove "@" in the object key instead of the email address.
This is the expected output :
// Expected output:
data = [
{ "date" : "17/03/2022", "count" : 2, "james" : 2 },
{
"date" : "17/05/2022",
"count" : 2,
"admin" : 1,
"secretary" : 1
},
{ "date" : "17/07/2022", "count" : 7, "staff" : 7 },
];
Notes:
- james is from [email protected] (1st element)
- admin and secretary are from [email protected] and [email protected], respectively (2nd element)
- staff is from [email protected] (3rd element) and so on.
- email as object keys are dynamic, meaning it can be "[email protected]", "[email protected]", etc.
I have tried, but yet not successful :
for (let i = 0; i < data.length; i++) {
let keys = Object.keys(data[i]);
console.log(`key-${i+1} :`, keys); // [ 'date', 'count', '[email protected]', '[email protected]' ]
let emails = keys.filter(index => index.includes("@"));
console.log(`email-${i+1} :`, emails); // [ '[email protected]', '[email protected]' ]
let nameList = [];
for (let i = 0; i < emails.length; i++) {
let name = emails[i].split("@")[0];
nameList.push(name);
}
console.log(`name-${i+1} :`, nameList); // [ 'admin', 'secretary' ]
}
Thanks in advance.