gpt4 book ai didi

javascript - Lodash key与数组具有相同的属性

转载 作者:行者123 更新时间:2023-12-03 01:57:36 24 4
gpt4 key购买 nike

我的数组中有一些对象:

"surcharges": [
{
"supplier": "XXXXX",
"name": "over_pkg_0",
"amount": 230
},
{
"supplier": "XXXXX",
"name": "over_pkg_1",
"amount": 54
},
{
"supplier": "YYYYY",
"name": "over_pkg_0",
"amount": 25
},
{
"supplier": "YYYYY",
"name": "over_pkg_1",
"amount": 25
}
];

我想使用 lodash 获得以下结果:

"surcharges": [
{
"XXXXX": [
{
"name": "over_pkg_0",
"amount": 230
},
{
"name": "over_pkg_1",
"amount": 54
}
],
},
{
"YYYYY": [
{
"name": "over_pkg_0",
"amount": 25
},
{
"name": "over_pkg_1",
"amount": 25
}
],
}
];

我能够生成类似的东西,但是键正在合并,我无法将它们变成数组。也许我应该在链中的某个地方使用 _.concat ,但我不知道如何使用。

尝试使用:

var finalsurcharges = _.chain(surcharges)
.keyBy('supplier')
.mapValues(v => _.omit(v, 'supplier'))
.value();

产品:

"finalsurcharges": {
"XXXXX": {
"name": "over_pkg_1",
"amount": 54
},
"YYYYY": {
"name": "over_pkg_1",
"amount": 25
}
}

最佳答案

使用_.groupBy()按键值对对象数组进行分组:

const data = { surcharges: [{"supplier":"XXXXX","name":"over_pkg_0","amount":230},{"supplier":"XXXXX","name":"over_pkg_1","amount":54},{"supplier":"YYYYY","name":"over_pkg_0","amount":25},{"supplier":"YYYYY","name":"over_pkg_1","amount":25}]};

const finalsurcharges = _(data.surcharges)
.groupBy('supplier')
.mapValues((g) => g.map(o => _.omit(o, 'supplier')))
.value();

console.log(finalsurcharges);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

关于javascript - Lodash key与数组具有相同的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50175202/

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