【发布时间】:2019-10-28 11:18:58
【问题描述】:
我正在尝试转换这个对象:
[
{
"keyword":"apple",
"category_1":"object",
"category_2":"living",
"category_3":"fruit",
"count":5
},
{
"keyword":"orange",
"category_1":"object",
"category_2":"living",
"category_3":"fruit",
"count":1
},
{
"keyword":"table",
"category_1":"object",
"category_2":"non living",
"category_3":"house item",
"count":3
},
{
"keyword":"cat",
"category_1":"object",
"category_2":"living",
"category_3":"animal",
"count":4
},
{
"keyword":"stadium",
"category_1":"place",
"category_2":"sport related",
"category_3":"indoor",
"count":2
}
]
变成这样的对象:
[
{
label: 'object',
count: 9,
childs: [
{
label: 'living',
count: 6,
childs: [
{
label: 'fruit',
count: 6,
childs: [
{
keyword: 'apple',
count: 5,
},
{
keyword: 'orange',
count: 1,
}
]
}
]
},
{
label: 'non living',
count: 3,
childs: [
{
label: 'animal',
count: 3,
childs: [
{
keyword: 'cat',
count: 3,
}
]
}
]
}
]
},
{
label: 'place',
count: 2,
childs: [
{
label: 'sport related',
count: 2,
childs: [
{
label: 'indoor',
count: 2,
childs: [
{
keyword: 'stadium',
count: 2,
}
]
}
]
}
]
}
]
我尝试以递归方式使用 Array.reduce,但我遇到了递归问题,我总是会碰壁。 如您所见,重点是将数组变成一个嵌套对象,将其元素按类别分组(计数部分不是必需的)
如果有人对此有任何后见之明
【问题讨论】:
-
为什么不用
children而不是childs? -
对象数不应该是 13 吗?
-
还有一只猫不见了,三张桌子;P
标签: javascript data-conversion