JS 数组根据某一字段值分组
本帖最后由 lucklys 于 2022-8-15 15:45 编辑[{id:1,name:'大'}, {id:2,name:'小'}, {id:3,name:'大'}, {id:4,name:'小'}, {id:5,name:'大'}, {id:6,name:'大'}, {id:7,name:'小'}, {id:7,name:'中'}, {id:7,name:'小'}, {id:7,name:'中'}]
比如我有一组数据 是这样子的,可能还会有超大 超小 之类的
我需要 把相同的name 放到一块
我该怎么做呀,整不会了。
let a = [
{ id: 1, name: '大' },
{ id: 2, name: '小' },
{ id: 3, name: '大' },
{ id: 4, name: '小' },
{ id: 5, name: '大' },
{ id: 6, name: '大' },
{ id: 7, name: '小' },
{ id: 7, name: '中' },
{ id: 7, name: '小' },
{ id: 7, name: '中' },
]
let newArr = []
let nameList = new Set(a.map(item => item.name))
nameList.forEach((item, index) => {
newArr = {
name: item,
goods: [],
}
a.forEach(items => {
if (item == items.name) {
newArr.goods.push(items)
}
})
})
console.log(newArr)
我自己想到这这种解决方法,还有更简单的吗~ 百度,js groupBy方法一大堆的 lodash groupBy const arr = [
{ id: 1, name: '大' },
{ id: 2, name: '小' },
{ id: 3, name: '大' },
{ id: 4, name: '小' },
{ id: 5, name: '大' },
{ id: 6, name: '大' },
{ id: 7, name: '小' },
{ id: 7, name: '中' },
{ id: 7, name: '小' },
{ id: 7, name: '中' }
]
const newarr = arr.reduce(function (pre, cur) {
const item = pre.find(p => p.name == cur.name)
if (item) {
item.data.push(cur)
} else {
pre.push({
name: cur.name,
data:
})
}
return pre
}, [])
const ids = arr.reduce(function (pre, cur) {
if (pre) {
pre.push(cur)
} else {
pre =
}
return pre
}, {})
console.log(JSON.stringify(newarr, null, 4))
console.log(JSON.stringify(ids, null, 4)) 52P 发表于 2022-8-15 14:58
const arr = [
{ id: 1, name: '大' },
{ id: 2, name: '小' },
牛啊,我从来都没用过这东西
页:
[1]