我得到了這個陣列:
[
name1,
email1@name1.com,
email2@name1.com,
email3@name1.com,
name2,
email1@name2.com,
name3,
name4,
email1@name4.com,
email2@name4.com,
email3@name4.com,
email4@name4.com,
email5@name4.com,
]
我需要從該陣列中決議它并創建一個如下所示的陣列:
[
{ dlName: < element without @ > , members: [<elements with @ >]},
{ dlName: < element without @ > , members: [<elements with @ >]},
{ dlName: < element without @ > , members: [<elements with @ >]}
]
例子:
[
HR,
someonefks@name.com,
fjkdafaldksjh@name.com,
sfafafads@name.com,
cyber,
fakdjfnakj@name.com,
fdsfasfasds@name.com,
accessibility,
accounting,
dasaasas@name.com,
klhdaflkaa@name.com
]
輸出:
[
{ dlName: HR , members: [someonefks@name.com,fjkdafaldksjh@name.com,sfafafads@name.com,]},
{ dlName: cyber , members:[fakdjfnakj@name.com,fdsfasfasds@name.com,]},
{ dlName: accesibility , members: []},
{ dlName: accounting , members: [dasaasas@name.com,klhdaflkaa@name.com]}
]
我怎樣才能得到這個輸出,我嘗試的一切都不適合我的需要。
提前致謝
uj5u.com熱心網友回復:
您可以通過查看字串來減少陣列。
如果您'@'將字串添加到最后一個物件中members,則將新物件添加到結果集中。
const
data = ['name1', '[email protected]', '[email protected]', '[email protected]', 'name2', '[email protected]', 'name3', 'name4', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]'],
result = data.reduce((r, v) => {
if (v.includes('@')) r[r.length - 1].members.push(v);
else r.push(({ dlName: v, members: [] }));
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/497572.html
標籤:javascript 数组 目的
