[英]Create an array of objects recursively based in array of objects
我有一個這樣的對象數組:
myArr = [
{ "id": "aaa.bbb" },
{ "id": "aaa.ccc" },
{ "id": "111.222" },
{ "id": "111.333" },
]
我的目標是能夠為 Id 的每個部分創建一個新數組,同時嵌套舊數組。 像這樣:
newArray = [
{
"id": "aaa",
"children": [{ "id": "aaa.bbb" }]
},
{
"id": "aaa",
"children": [{ "id": "aaa.ccc" }]
},
{...}
]
如果有一個更大的 Id,這個想法是能夠用多個子字符串來做
您可以使用 map 遍歷數組並就地改變對象
myArr = [ { "id": "aaa.bbb" }, { "id": "aaa.ccc" }, { "id": "111.222" }, { "id": "111.333" }, ] result=myArr.map((o)=>({["id"]:o.id.split(".")[0],["children"]:[o]})) console.log(result)
或者你可以使用 reduce
myArr = [ { "id": "aaa.bbb" }, { "id": "aaa.ccc" }, { "id": "111.222" }, { "id": "111.333" }, ] result=myArr.reduce((acc,curr)=>acc=[...acc,{["id"]:curr.id.split(".")[0],["children"]:[curr]}],[]) console.log(result)
使用Array.prototype.map
。
const newArray = myArr.map( function( e ) {
const oldId = e.id;
const newElement = {
id: oldId.split( '.' )[0],
children: [ e ]
};
return newElement
} );
簡化:
const newArray = myArr.map( function( e ) {
return {
id: e.id.split( '.' )[0],
children: [ e ]
};
} );
更遠:
const newArray = myArr.map( e => { id: e.id.split( '.' )[0], children: [ e ] } );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.