以前,我的数组的结构是:
[
{
"id": "Ddfwe23224533",
"kind": "PEAK_EXPERIENCE",
"title": "IP - Collective Identity",
},
{
"id": "Ddfwe23224534",
"kind": "PEAK_EXPERIENCE",
"title": "IP - Collective Identity 2",
},
.....
]
我创建了一个名为flatToHierarchy的函数来对数组中的元素进行分组。代码如下:
export const flatToHierarchy = (arr, prop) => arr.reduce((accumulator, currentItem) => {
const items = accumulator;
const propValue = currentItem[prop];
items[propValue] = items[propValue]
? [...items[propValue], currentItem]
: [currentItem];
return items;
}, {});
flatToHierarchy(elements, 'kind')
很好用。
[
{
"entity": {
"id": "Ddfwe23224533",
"kind": "PEAK_EXPERIENCE",
"title": "IP - Collective Identity",
},
entity_id: "jj98834jfj983"
},
{
"entity": {
"id": "Ddfwe23224534",
"kind": "PEAK_EXPERIENCE",
"title": "IP - Collective Identity 2",
},
entity_id: "jj98834jfdf83"
},
.....
]
所以,对于按元素类型分组数组,我这样称呼它:
flatToHierarchy(elements, 'entity.kind')
现在,它给我的结果是:
{
undefined: [....element1, ....element2 ]
}
{
PEAK_EXPERIENCE: [....element1, ....element2 ]
}
我对此进行了深入研究,发现数组不能通过这种方式访问:
array['something.something']
需要通过以下方式访问:
array['something']['something']
所以,我改变了我的功能,但我卡住了。以下是我更改的函数:
export const flatToHierarchy = (arr, prop) => arr.reduce((accumulator, currentItem) => {
const items = accumulator;
const props = prop.split('.').map(p => [p]);
console.log(props);
const propValue = currentItem[prop];
console.log(currentItem...props); // how to spread the array here?
items[propValue] = items[propValue]
? [...items[propValue], currentItem]
: [currentItem];
return items;
}, {});
电流输入示例:
[
{
"entity": {
"id": "Ddfwe23224533",
"kind": "PEAK_EXPERIENCE",
"title": "IP - Collective Identity",
},
entity_id: "jj98834jfj983"
},
{
"entity": {
"id": "Ddfwe23224534",
"kind": "PEAK_EXPERIENCE",
"title": "IP - Collective Identity 2",
},
entity_id: "jj98834jfdf83"
},
{
"entity": {
"id": "Ddfwe23224594",
"kind": "PEAK_EXPERIENCE2",
"title": "IP - Collective Identity 6",
},
entity_id: "jj98834jfdf33"
},
]
所需输出示例:
{
PEAK_EXPERIENCE: [
{
"entity": {
"id": "Ddfwe23224533",
"kind": "PEAK_EXPERIENCE",
"title": "IP - Collective Identity",
},
entity_id: "jj98834jfj983"
},
{
"entity": {
"id": "Ddfwe23224534",
"kind": "PEAK_EXPERIENCE",
"title": "IP - Collective Identity 2",
},
entity_id: "jj98834jfdf83"
},
],
PEAK_EXPERIENCE2: [
{
"entity": {
"id": "Ddfwe23224594",
"kind": "PEAK_EXPERIENCE2",
"title": "IP - Collective Identity 6",
},
entity_id: "jj98834jfdf33"
},
],
}
更新2:
flatToHierarchy(array, string);
例子:
flatToHierarchy(elements, 'kind');
flatToHierarchy(elements, 'entity.kind');