[英]How to group an array of objects based on a dot-separated string of numbers
I have an array of objects as the following我有一个对象数组如下
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' }
];
I'd like to create a new array to include the children under their parent based on id
property as the following我想创建一个新数组,以根据
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' } ]
}
]
I'm not sure how to do it or from where to start我不确定该怎么做或从哪里开始
Use a map to keep track of parents and children, then get the entries that are the roots as your result:使用 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.