热搜:fiddler git ip ios 代理
历史搜索

vue 将后台返回的对象数组根据某个字段组成新的对象数组?

游客2024-10-23 12:03:01

vue 如何将后台返回的对象数组根据某个字段组成新的对象数组,这也是我在最近项目中遇到的问题,特此整理一下,方便自己后期学习,也希望对需要的小伙伴提供帮助。

假如后台返回给我们如下数据结构:

var list = [
    {
        "id": 1,
        "modes": "CHARTBAR_1",
    },
    {
        "id": 2,
        "modes": "CHARTBAR_1",
    },
    {
        "id": 3,
        "modes": "CHARTBAR_2",
    },
    {
        "id": 4,
        "modes": "CHARTBAR_2",
    },
    {
        "id": 5,
        "modes": "CHARTBAR_3",
    },
    {
        "id": 6,
        "modes": "CHARTBAR_4",
    },
    {
        "id": 7,
        "modes": "CHARTBAR_4",
    },
    {
        "id": 8,
        "modes": "CHARTBAR_1",
    },
    {
        "id": 9,
        "modes": "CHARTBAR_1",
    },
    {
        "id": 10,
        "modes": "CHARTBAR_1",
    },
]

然后,我们要让上面的数据根据 modes 字段重新组合成新的对象数组,比如整合成下面这样:

[{
    "modes": "CHARTBAR_1",
    "list": [{
        "id": 1,
	"modes": "CHARTBAR_1"
    }, {
	"id": 2,
	"modes": "CHARTBAR_1"
    }, {
	"id": 8,
	"modes": "CHARTBAR_1"
    }, {
	"id": 9,
	"modes": "CHARTBAR_1"
    }, {
	"id": 10,
	"modes": "CHARTBAR_1"
    }]
}, {
    "modes": "CHARTBAR_2",
    "list": [{
	"id": 3,
	"modes": "CHARTBAR_2"
    }, {
	"id": 4,
	"modes": "CHARTBAR_2"
    }]
}, {
    "modes": "CHARTBAR_3",
    "list": [{
	"id": 5,
	"modes": "CHARTBAR_3"
    }]
}, {
    "modes": "CHARTBAR_4",
    "list": [{
	"id": 6,
	"modes": "CHARTBAR_4"
    }, {
	"id": 7,
	"modes": "CHARTBAR_4"
    }]
}]

实现方法:

function getListGroupBy(list, key) {
    var keysArr = list.map(item=>item[key])
    var keys = [...new Set(keysArr)]
    var newList = keys.map(item=> {
        return {
            [key]: item,
            list: list.filter(i=>i[key] == item)
        }
    })
    return newList
}

var newList = getListGroupBy(list, 'modes')
console.log(newList)

就是这么简单!

vue 将后台返回的对象数组根据某个字段组成新的对象数组? 1

标签:vue