首页 > 解决方案 > 如何按 ID 数据分组(映射)?

问题描述

我如何对我的数据进行分组CustomerID

它不起作用,我正在尝试不同的方式,但我想我不理解这种结构

这是我的代码:

function CustomerGroup() {
this.$http.post(auth.API_URL + 'api/ProblemsSupports/ProblemsList', null, {
    headers: {
        'Authorization': 'Bearer ' + auth.getAuthHeader()
    }
}).then((response) => {
    this.problemitems = response.body
    const map = this.problemitems.map(e => (map[e.CustomerID] = map[e.CustomerID]))
    return map
    this.progress = false
}, (response) => {
    if (response.status === 0) {
        this.text1 = ' !!!'
        this.snackbar = true
        this.progress = false
    } else {
        this.text1 = '!!!!!!'
        this.snackbar = true
        this.progress = false
    }
})
}

标签: arraysvue.jsvuejs2

解决方案


例如,您可以使用此功能:

groupBy (list, keyValue) {
const map = new Map()
list.forEach((item) => {
  const key = item[keyValue]
  const collection = map.get(key)
  if (!collection) {
    map.set(key, [item])
  } else {
    collection.push(item)
  }
})
return Array.from(map.values())  
}

然后就叫它

const map = groupBy(this.problemitems, 'CustomerID')

你可以在 Vue 方法中使用函数,然后不要忘记this


推荐阅读