# 整合对象数组的算法问题，求解！

LIXINCHAO
• 268

``````const resData = [
{dict: '东北', type: '二线', isProvinceCapital: '是', city: '哈尔滨', money: 100},
{dict: '东北', type: '二线', isProvinceCapital: '是', city: '沈阳', money: 200},
{dict: '东北', type: '三线', isProvinceCapital: '否', city: '大兴安岭', money: 300},
{dict: '华东', type: '一线', isProvinceCapital: '是', city: '上海', money: 400},
{dict: '华东', type: '二线', isProvinceCapital: '是', city: '杭州', money: 500},
{dict: '华东', type: '二线', isProvinceCapital: '否', city: '宁波', money: 600}
];
// 处理数据的方法!
function formatData(keys) {

}``````

``````// 1
// 输入 ['isProvinceCapital']
// 输出如下：
let list = [
{
isProvinceCapital: '是',
children: [
{dict: '东北', type: '二线', isProvinceCapital: '是', city: '哈尔滨', money: 100},
{dict: '东北', type: '二线', isProvinceCapital: '是', city: '沈阳', money: 200},
{dict: '华东', type: '一线', isProvinceCapital: '是', city: '上海', money: 400},
{dict: '华东', type: '二线', isProvinceCapital: '是', city: '杭州', money: 500},
]
},
{
isProvinceCapital: '否',
children: [
{dict: '东北', type: '三线', isProvinceCapital: '否', city: '大兴安岭', money: 300},
{dict: '华东', type: '二线', isProvinceCapital: '否', city: '宁波', money: 600}
]
}
];

// 2
// 输入 ['dict', 'type']
// 输出如下：
let list2 = [
{
dict: '东北',
children: [
{
dict: '东北',
type: '二线',
children: [
{dict: '东北', type: '二线', isProvinceCapital: '是', city: '哈尔滨', money: 100},
{dict: '东北', type: '二线', isProvinceCapital: '是', city: '沈阳', money: 200}
]
},
{
dict: '东北',
type: '三线',
children: [
{dict: '东北', type: '三线', isProvinceCapital: '否', city: '大兴安岭', money: 300}
]
}
]
},
{
dict: '华东',
children: [
{
dict: '华东',
type: '一线',
children: [
{dict: '华东', type: '一线', isProvinceCapital: '是', city: '上海', money: 400}
]
},
{
dict: '华东',
type: '二线',
children: [
{dict: '华东', type: '二线', isProvinceCapital: '是', city: '杭州', money: 500},
{dict: '华东', type: '二线', isProvinceCapital: '否', city: '宁波', money: 600}
]
},
]
}
];``````

`formatData`方法如何实现，感谢

##### 2个回答
✓ 已被采纳
``````const formatData = (data, keys) => Object.entries(
data.reduce((acc, item) => (
(acc[item[keys[0]]] ??= []).push(item),
acc
), {})
).map(([ keyvalue, children ]) => ({
[keys[0]]: keyvalue,
children: keys.length > 1
? formatData(children, keys.slice(1)).map(child => ({
[keys[0]]: keyvalue,
...child
}))
: children
}))``````

``````import _ from "lodash";

function formatData(data, keys) {
if (!(keys?.length)) { return data; }
const [key, ...restKeys] = keys;
return _(resData)
.groupBy(it => it[key])
.entries()
.map(([name, children]) => ({
[key]: name,
children: formatData(children, restKeys)
}))
.value();
}``````
##### 撰写回答
###### 你尚未登录，登录后可以
• 和开发者交流问题的细节
• 关注并接收问题和回答的更新提醒
• 参与内容的编辑和改进，让解决方法与时俱进