我有一个对象数组:
let data = [
{ "date" : "17/03/2022", "count" : 2, "james@email.net" : 2 },
{
"date" : "17/05/2022",
"count" : 2,
"admin@email.com" : 1,
"secretary@email.uk" : 1
},
{ "date" : "17/07/2022", "count" : 7, "staff@email.us" : 7 },
];
我想删除对象键中的"@",而不是电子邮件地址。
这是预期输出:
// 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 },
];
注:
- james is from james@email.net (1st element)
- admin and secretary are from admin@email.com and secretary@email.uk, respectively (2nd element)
- staff is from staff@email.us (3rd element) and so on.
- email as object keys are dynamic, meaning it can be "johndoe@email.co.uk", "mary@email.net", etc.
我试过了,但没有成功:
for (let i = 0; i < data.length; i++) {
let keys = Object.keys(data[i]);
console.log(`key-${i+1} :`, keys); // [ 'date', 'count', 'admin@email.com', 'secretary@email.uk' ]
let emails = keys.filter(index => index.includes("@"));
console.log(`email-${i+1} :`, emails); // [ 'admin@email.com', 'secretary@email.uk' ]
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' ]
}
先谢了。
3条答案
按热度按时间quhf5bfb1#
您可以创建一个函数,在
@
处拆分对象键的键,并使用Object.fromEntries()
创建一个新对象。下面是一个片段:
如果
Object.fromEntries()
不受支持,您可以使用一个简单的循环遍历数组,然后遍历每个对象来创建新对象,如下所示:bybem2ql2#
试试这个简单的方法:
6l7fqoea3#
你能试试这个吗?