繁体   English   中英

如何根据以点分隔的数字字符串对对象数组进行分组

[英]How to group an array of objects based on a dot-separated string of numbers

我有一个对象数组如下

const sample = [
    { id: '1' },
    { id: '1.1' },
    { id: '1.1.1' },
    { id: '1.1.2' },
    { id: '1.2' },
    { id: '1.2.1' },
    { id: '1.2.1.1' },
    { id: '2' },
    { id: '2.1' }
];

我想创建一个新数组,以根据id属性将子项包含在其父项下,如下所示

[
    {
        id: '1',
        children: [
            {
                id: '1.1',
                children: [
                    { id: '1.1.1' },
                    { id: '1.1.2' }
                ]
            },
            {
                id: '1.2',
                children: [
                    {
                        id: '1.2.1',
                        children: [{ id: '1.2.1.1' }]
                    }
                ]
            }
        ]
    },
    {
        id: '2',
        children: [ { id: '2.1' } ]
    }
]

我不确定该怎么做或从哪里开始

使用 map 跟踪父母和孩子,然后获取作为根的条目作为结果:

 const data = [ { id: '1' }, { id: '1.1' }, { id: '1.1.1' }, { id: '1.1.2' }, { id: '1.3' }, { id: '1.3.1' }, { id: '1.3.1.1' }, { id: '2' }, { id: '2.1' } ]; const map = new Map(); data.forEach(({ id }) => { // exclude last bit to get parent id const parent = id.split(".").slice(0, -1).join("."); // our entry - needs to be like this since // we want a reference to the same object const entry = { id, children: [] }; // won't run if this is a root if (parent) // add child to parent map.get(parent).children.push(entry); // add to map map.set(id, entry); }); const result = Array.from(map) // get roots - keys that only have one part.filter(([key]) => key.split(".").length === 1) // map to entry values.map(([, value]) => value); console.log(result);
 .as-console-wrapper { max-height: 100% !important }

暂无
暂无

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

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