vue||Js数组对象属性值分类,一个数组拆分为多个数组
原数据data:[{id: 1, name: '张三', text: '呵呵'},{id: 2, name: '张三', text: '无聊'},{id: 3, name: '张三', text: '玩玩'},{id: 4, name: '李四', text: '啊啊'},{id: 5, name: '王五', text: '偷偷'},{id: 6, name: '赵六
·
原数据
data:[
{id: 1, name: '张三', text: '呵呵'},
{id: 2, name: '张三', text: '无聊'},
{id: 3, name: '张三', text: '玩玩'},
{id: 4, name: '李四', text: '啊啊'},
{id: 5, name: '王五', text: '偷偷'},
{id: 6, name: '赵六', text: '试试'}
]
我们现在需要根据name这个属性拆分分类,同一类的要放在一个数组里面,代码。
data.forEach(item => {
const parent = dataarr.find(c => c.name === item.name)
if (parent) {
parent.childs.push(item)
} else {
const obj = {
name: item.name,
childs: [item]
}
dataarr.push(obj)
}
})
分类后结果得到
[
{
"name": "张三",
"childs": [
{
"id": 1,
"name": "张三",
"text": "呵呵"
},
{
"id": 2,
"name": "张三",
"text": "无聊"
},
{
"id": 3,
"name": "张三",
"text": "玩玩"
}
]
},
{
"name": "李四",
"childs": [
{
"id": 4,
"name": "李四",
"text": "啊啊"
}
]
},
{
"name": "王五",
"childs": [
{
"id": 5,
"name": "王五",
"text": "偷偷"
}
]
},
{
"name": "赵六",
"childs": [
{
"id": 6,
"name": "赵六",
"text": "试试"
}
]
}
]
更多推荐
已为社区贡献6条内容
所有评论(0)