简体   繁体   English

基于对象数组递归创建对象数组

[英]Create an array of objects recursively based in array of objects

I have an array of objects like this:我有一个这样的对象数组:

myArr = [
    { "id": "aaa.bbb" },
    { "id": "aaa.ccc" },
    { "id": "111.222" },
    { "id": "111.333" },
]

My goal is to be able to have a new array for every part of the Id, while nesting the old array.我的目标是能够为 Id 的每个部分创建一个新数组,同时嵌套旧数组。 Like this:像这样:

newArray = [
    {
      "id": "aaa",
      "children": [{ "id": "aaa.bbb" }] 
    },
    {
      "id": "aaa",
      "children": [{ "id": "aaa.ccc" }] 
    },
    {...}
]

The idea is to be able to do It with multiple substrings if there is a bigger Id如果有一个更大的 Id,这个想法是能够用多个子字符串来做

You could use map to iterate through the array and mutate the objects in place您可以使用 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)

alternatively you could use reduce或者你可以使用 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)

Use Array.prototype.map .使用Array.prototype.map

const newArray = myArr.map( function( e ) {

    const oldId = e.id;    
    const newElement = {
        id: oldId.split( '.' )[0],
        children: [ e ]
    };
    return newElement
} );

Simplified:简化:

const newArray = myArr.map( function( e ) {
    return {
        id: e.id.split( '.' )[0],
        children: [ e ]
    };
} );

Further:更远:

const newArray = myArr.map( e => { id: e.id.split( '.' )[0], children: [ e ] } );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM