【JS】对数据分组处理

按照“谁”分组,就让这个“谁”作为结果对象的 key,然后把匹配的数据分别放在这些 key 对应的 value 下面

 

<html>
    <head>
        <title>对数据分组处理</title>
    </head>
    <body>
    </body>
    <script>
        const data = [
            {
                name: 'zhangsan',
                gender: 'male',
                age: 18
            },
            {
                name: 'lisi',
                gender: 'male',
                age: 20
            },
            {
                name: 'wangwu',
                gender: 'female',
                age: 19
            },
            {
                name: 'zhaoliu',
                gender: 'female',
                age: 9
            },
            {
                name: 'hahh',
                gender: 'male',
                age: 20
            },
            {
                name: 'heihei',
                gender: 'female',
                age: 19
            },
        ]

        function handleDepartData(data, key) {
            let obj = {}
            data.forEach(item => {
                let value = item[key]
                obj[value] = obj[value] || []
                obj[value].push(item)
            })
            return obj
        }
        const dataHandled = handleDepartData(data, 'age')
        console.log(dataHandled)
    </script>
</html>

按照 age 分组

 

按照 gender 分组

 

 

vue

<script setup lang="ts">
import { onMounted } from 'vue';
import { p, data } from './contants'
import type { Person, PersonParams, ObjType } from './types'
import { ref } from 'vue'

function handleDepartData(data: Person[], key: PersonParams) {
  let obj: ObjType = {}
  data.forEach((item: Person) => {
    const value = item[key]
    obj[value] = obj[value] ?? []
    obj[value].push(item)
  })
  p(`obj: ${obj}`)
  return obj
}

let personDepartedData = ref()

onMounted(() => {
  personDepartedData.value = handleDepartData(data, 'age')
})
</script>

<template>
  <div v-for="(value, key) in personDepartedData" :key="key">
    <h3>{{ key }}</h3>
    <ul>
      <li v-for="item in value" :key="item.name">
        {{ item.name }}
      </li>
    </ul>
  </div>
</template>

<style scoped>
</style>

 

posted @ 2023-09-06 21:30  zjy4fun  阅读(98)  评论(0编辑  收藏  举报