结果图:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
let data = [{
key: 'xxx',
name: 'yiyi',
age: 12,
money: 10
},
{
key: 'sss',
name: 'iii',
age: 13,
money: 100
},
{
key: 'ddd',
name: 'ooo',
age: 13,
money: 50
},
{
key: 'sss',
name: 'mmm',
age: 50,
money: 90
},
];
function group(data, key) {
let dataKey = []
let newArr = []
data.forEach((item, index) => {
//若已存在
if (dataKey.includes(item[key])) {
// 寻找索引
const indexLocation = newArr.findIndex(item_ => item_[key] == item[key])
// 数据加入
newArr[indexLocation].children.push(item)
} else {
// 若不存在
dataKey.push(item[key])
newArr.push({
id: Math.random().toString(36).slice(-6),
key: item[key],
children: [...[item]]
})
}
})
return newArr
}
console.log(group(data, "key"))
</script>
</body>
</html>