gpt4 book ai didi

javascript - Lodash 对对象数组中的项目进行分组

转载 作者:行者123 更新时间:2023-11-30 19:50:34 24 4
gpt4 key购买 nike

我有一个带 band 属性的对象数组。我想根据乐队对他们进行分组

我试过 _groupBy 但没有得到预期的结果

    var data=[
{
"tOffice": 123,
"cType": 5000,
"band": -4877,
"minCh": 12,
"maxCh": 20
},
{
"tOffice": 123,
"cType": 5000,
"band": -4877,
"minCh": 1,
"maxCh": 2
},
{
"tOffice": 123,
"cType": 5000,
"band": -4877,
"minCh": 11,
"maxCh": 12
},
{
"tOffice": 123,
"cType": 6000,
"band": -5877,
"minCh": 11,
"maxCh": 12
},
{
"tOffice": 456,
"cType": 5000,
"band": -4544,
"minCh": 12,
"maxCh": 20
},
{
"tOffice": 456,
"cType": 5000,
"band": -4544,
"minCh": 10,
"maxCh": 11
},
{
"tOffice": 456,
"cType": 6000,
"band": -5211,
"minCh": 12,
"maxCh": 20
},
{
"tOffice": 456,
"cType": 6000,
"band": -5211,
"minCh": 12,
"maxCh": 20
},
{
"tOffice": 456,
"cType": 6000,
"band": -5211,
"minCh": 12,
"maxCh": 20
}
];

预期输出:

var expectedResult = [{
tOffice: 123,
bandType: [{
band: '123-5000',
minMaxCharge: [{
minCh: 12,
maxCh: 20
}, {
minCh: 1,
maxCh: 2
}, {
minCh: 11,
maxCh: 12
}]
},
{
band: '123-6000',
minMaxCharge: [{
minCh: 11,
maxCh: 12
}]

}
]
}, {
tOffice: 456,
bandType: [{
band: '456-5000',
minMaxCharge: [{
minCh: 12,
maxCh: 20
}, {
minCh: 10,
maxCh: 11
}]
},
{
band: '456-6000',
minMaxCharge: [{
minCh: 12,
maxCh: 20
}, {
minCh: 12,
maxCh: 20
}]
}
]
}]

预期结果应包含最多 2 个组合(5000 和 6000)的 tOffice,band 是 tOffice+cType 的组合。

_.chain(data).groupBy("band").map(function(v, i) {
return {

}
})

我已经尝试了一些 ES6 方式,发现 lodash 方法将是一个不错的选择,但我不知道这一点

最佳答案

这是一个普通的 js 解决方案。你可以使用 reduceObject.values 做这样的事情

var data=[{"tOffice":123,"cType":5000,"band":-4877,"minCh":12,"maxCh":20},{"tOffice":123,"cType":5000,"band":-4877,"minCh":1,"maxCh":2},{"tOffice":123,"cType":5000,"band":-4877,"minCh":11,"maxCh":12},{"tOffice":123,"cType":6000,"band":-5877,"minCh":11,"maxCh":12},{"tOffice":456,"cType":5000,"band":-4544,"minCh":12,"maxCh":20},{"tOffice":456,"cType":5000,"band":-4544,"minCh":10,"maxCh":11},{"tOffice":456,"cType":6000,"band":-5211,"minCh":12,"maxCh":20},{"tOffice":456,"cType":6000,"band":-5211,"minCh":12,"maxCh":20},{"tOffice":456,"cType":6000,"band":-5211,"minCh":12,"maxCh":20}];

const merged = data.reduce((r,{tOffice, cType, minCh, maxCh})=>{
const office = r[tOffice] = r[tOffice] || {tOffice, bandType:{}};
const band = `${tOffice}-${cType}`

const nested = office.bandType[band]
= office.bandType[band] || {band, minMaxCharge:[]};

nested.minMaxCharge.push({minCh, maxCh})
return r
},{})

const final = Object.values(merged);
final.forEach(a => a.bandType = Object.values(a.bandType))

console.log(final)

关于javascript - Lodash 对对象数组中的项目进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54517121/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com