那些后端不处理就丢给前端的数据: 数组对象的value值相等 合并成新的数组对象

我正在参加「掘金·启航计划」

js 数组对象的value值相等 合并成新的数组对象

我们经常遇到各种数据处理,尤其是数组对象的处理,我们想把数组对象里相同key和value的值组合到一起方便渲染,如果后端不处理,这个数据就需要前端去做处理

比如我遇到的一组数据如下:

let array = [
    { name: '法外狂徒',age: 20,school: '北大青鸟' },
    { name: '张三',age: 21,school: '蓝翔技校' },
    { name: "黄二狗", age: 19, school: "蓝翔技校" },
    { name: '非常可乐',age: 18,school: '北大青鸟' },
    { name: '可口可乐',age: 19,school: '北大青鸟' },
    { name: '百事可乐',age: 21,school: '哈尔滨佛学院' },
]

把相同学校的同学放在一起,组装起来如下:


let data = [
  {
    school: "北大青鸟",
    children: [
      { name: "法外狂徒", age: 20, school: "北大青鸟" },
      { name: "非常可乐", age: 18, school: "北大青鸟" },
       { name: '可口可乐',age: 19,school: '北大青鸟' },
    ]
  },
  {
    school: "蓝翔技校",
    children: [
      { name: "张三", age: 21, school: "蓝翔技校" },
      { name: "黄二狗", age: 19, school: "蓝翔技校" },
    ]
  },
  {
    school: "哈尔滨佛学院",
    children: [
      { name: "百事可乐", age: 21, school: "哈尔滨佛学院" },
    ]
  },
]

使用空对象接收数据(最开始最常用的)

let object = {}
 
array.forEach((item) => {
 
  let { school } = item
 
  if (!object[school]) {
 
    object[school] = {
 
      school,
      children: []
    }
 
  }
 
  object[school].children.push(item)
 
})
 
console.log(Object.values(object))

使用findIndex方法

let arr2 = []
 
array.forEach((item, index) => {
 
    let has = arr2.findIndex(o => o.school === item.school);
 
    if (has == -1) {
 
        arr2.push({
 
            school: item.school,
 
            age: item.age,
 
            children: [item]
 
        })
 
    } else {
 
        arr2[has].children.push(item)
 
    }
 
})

利用find查找来处理

let newList = [] 
 
array.forEach(item => { 
 
  let newItem = newList.find((i) => i.school == item.school) 
 
  if (!newItem) { 
 
    newList.push({ school: item.school, children: [item] }) 
 
  } else { 
 
    newItem.children.push(item) 
 
  } 
 
})

使用hash对象

let hash = {}; 
 
let index = 0; 
 
let array1 = []; 
 
array.forEach(function(item) { 
 
  let school = item.school; 
 
  hash[school] ? array1[hash[school] - 1].children.push(item) : hash[school] = ++index && res.push(
 
    { 
 
      children: [item], 
 
      school: school, 
 
      age: item.age 
 
    }
 
  ) 
 
})

利用reduce方法进行处理

let Obj = array.reduce((pre,cur,index)=> { 
 
  if(!pre[cur.school]){ 
 
    pre[cur["school"]] =[cur] 
 
  } else { 
 
    pre[cur.school].push(cur) 
 
  } 
 
  return pre; 
 
},{}) 
 
let aff= Object.keys(Obj).map((item)=>{
 
  return { 
 
    school:item, 
 
    children:Obj[item] 
 
  }
 
})

原文链接:https://juejin.cn/post/7229843601735548985 作者:夏目和友人

(0)
上一篇 2023年5月6日 上午10:10
下一篇 2023年5月6日 上午10:21

相关推荐

发表回复

登录后才能评论