我在数组中有几个对象:
blob.getBinaryStream();
我想使用lodash得到以下结果:
"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
}
];
我能够生成类似的东西,但是密钥正在合并,我无法将它们变成一个数组。 Probaly我应该在链中的某个地方使用"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();
答案 0 :(得分:1)
使用_.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>
&#13;