在后端返回的数据中,可能不太满意,所以需要自己重构数据。
原始数据
javascript
let arr = [
{title:"光头强",age:18,id:"0"},
{title:"孙悟空",age:18,id:"9"},
{title:"熊大",age:18,id:"0"},
{title:"猪八戒",age:18,id:"9"},
{title:"白龙马",age:18,id:"9"},
{title:"小猪佩奇",age:18,id:"4"},
{title:"熊二",age:18,id:"0"},
{title:"乔治",age:18,id:"4"},
{title:"小羊苏西",age:18,id:"4"}
]
现在要重构数据相同id的,放在同一个对象中,id作为key,其他作为value
方法一
javascript
// 对数据进行转换
const testGroup = {}
// 思路一:两次循环
for(let item of arr) {
testGroup [item.id] = []
}
for(let item of arr) {
const valueArray = testGroup [item.id]
valueArray.push(item)
}
打印结果
方法二
javascript
// 思路二: 一次循环
// 对数据进行转换
const testGroup = {}
for (const item of arr) {
let valueArray = testGroup [item.id]
if (!valueArray) {
valueArray = []
swipeGroup[item.id] = valueArray
}
valueArray.push(item)
}
打印结果
大概就是这样,数据重构