问题记录(1)—数组对象分组、数组去重、数组转json

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;
};

 

  • 19
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值