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

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个回答

``````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();
}``````