1、数组对象分组
将oldData的转成newData的数据结构
const oldData = [
{
id:1,
name:'张三',
time: '2021-10-13'
},
{
id:2,
name:'李四',
time: '2021-10-12'
},
{
id:3,
name:'王王',
time: '2021-10-13'
}
]
newData = [
{
time: '2021-10-13',
data: [
{
id:1,
name:'张三',
time: '2021-10-13'
},
{
id:3,
name:'王五',
time: '2021-10-13'
},
]
},
{
time: '2021-10-12',
data: [
{
id:2,
name:'李四',
time: '2021-10-12'
}
]
}
]
function groupData(arr, fun) {
const groups = {}
arr.forEach((el) => {
const group = fun(el)
groups[group] = groups[group] || []
groups[group].push(el)
})
return Object.keys(groups).map((group) => {
// 更改data的数据结构 可以改变新数据的结构 data即为newData的数组中每个数据的结构
let data = {
time: group,
data: groups[group]
}
return data
})
},
function getNewData(oldData, prop) {
const newData = this.groupData(oldData, (item) => {
return item[prop]
})
return newData
},
// oldData => 原始数据 'time' => 按time属性进行分组
const newData = getNewData(oldData, 'time')
2、数组reduce方法
/**
arr.reduce(callback,[initialVaue])
callback(执行数组中每个值的函数,包含四个参数)
1、previousValue(上一次调用返回的值,或者是提供的初始值initialValue)
2、currentValue(数组中当前被处理的元素)
3、index (当前元素在数组中的索引)
4、array(调用reduce的数组)
initialValue(作为第一次调用 callback的第一个参数)
**/
let arr = [1,3,4,4,5,6,7,1]
let newArr = arr.reduce((pre,cur,index,arr) =>{
if(!pre.includes(cur)){
return pre.concat(cur)
}else {
return pre
}
},[])
const result = tableData.value.reduce((acc, curr) => {
const index = acc.findIndex((item) => item.id === curr.id)
if (index < 0) {
acc.push(curr)
}
return acc
}, [])
3、数组转json
const transferJson = (array) => {
const json = {};
for (let index in array) {
const item = array[index];
let newKey, newValue;
for (let key in item) {
if (key == "value") {
newKey = item[key];
}
if (key == "label") {
newValue = item[key];
}
}
json[newKey] = newValue;
}
return json;
};