我有一个json列表,我试图用两个键重新组合这个地图中的对象。暂时我只使用lodash groupBy成功地使用一个键进行分组,但是我无法找到正确的方法来创建行键并将这个新数组中的size / qty分组。我可以在我的代码中使用ES6或lodash
const colorsMap= _.groupBy(colors, 'Id');
我的初始json看起来像这样:
colors = [
{
"Id": "1",
"color": "red",
"size": "10"
"QTY": "2000"
"ref": "tr"
},
{
"Id": "1",
"color": "red",
"size": "25"
"QTY": "3000"
"ref": "tr"
},
{
"Id": "1",
"color": "blue",
"size": "15"
"QTY": "2050"
"ref": "gt",
},
{
"Id": "2",
"color": "red",
"size": "18"
"QTY": "2010"
"ref": "tt"
},
]
我想尝试这样的事情
[
"1": [
{
"Id": "1",
"color": "red",
"row": [
{
"size": "10"
"QTY": "2000"
},
{
"size": "25"
"QTY": "3000"
},
{
"size": "15"
"QTY": "0"
}
],
"ref": "tr"
},
{
"Id": "1",
"color": "blue",
"row": [
{
"size": "10"
"QTY": "0"
},
{
"size": "25"
"QTY": "0"
},
{
"size": "15"
"QTY": "2050"
}
],
"ref": "gt",
}
],
"2": [
{
"Id": "2",
"color": "red",
"row": [
{
"size": "18"
"QTY": "2010"
}
],
"ref": "tt"
}
]
]
答案 0 :(得分:1)
按ID对颜色进行分组后,再按颜色分组,并将第二组的值映射到您需要的对象:
const colors = [{"Id":"1","color":"red","size":"10","QTY":"2000","ref":"tr"},{"Id":"1","color":"red","size":"25","QTY":"3000","ref":"tr"},{"Id":"1","color":"blue","size":"15","QTY":"2050","ref":"gt"},{"Id":"2","color":"red","size":"18","QTY":"2010","ref":"tt"}];
const result = _(colors)
.groupBy('Id') // group by id
.mapValues((values) => _(values) // map the values
.groupBy('color') // group by color
.mapValues((v) => ({ // map the resulting arrays
/* get the id and color from the 1st item in the array */
id: v[0].Id,
color: v[0].color,
rows: v.map(({ size, QTY }) => ({ // map all elements to row objects
size,
QTY
}))
}))
.value())
.value();
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>