如何从JSON对象数组中对JSON对象进行分组?

时间:2019-11-21 21:32:14

标签: javascript node.js lodash

这是一个JSON对象数组,该数组具有要按其分组的数组值(拉式唯一):

Tile

最后我需要得到:

let myArray = [
    {
        "_id": "1",
        "subdata": [
            {
                "subid": "11",
                "name": "A"
            },
            {
                "subid": "12",
                "name": "B"
            }
        ]
    },
    {
        "_id": "2",
        "subdata": [
            {
                "subid": "12",
                "name": "B"
            },
            {
                "subid": "33",
                "name": "E"
            }
        ]
    }
]

我尝试过lodash失败了:

[
    {
        "subid": "11",
        "name": "A"
    },
    {
        "subid": "12",
        "name": "B"
    },
    {
        "subid": "33",
        "name": "E"
    }
]

我当然可以一次一扫每个数组元素,但是认为用lodash可以很容易地做到这一点

1 个答案:

答案 0 :(得分:1)

使用_.flatMap()获取所有subdata项的数组,然后将_.uniqueBy()subid结合使用:

const myArray = [{"_id":"1","subdata":[{"subid":"11","name":"A"},{"subid":"12","name":"B"}]},{"_id":"2","subdata":[{"subid":"12","name":"B"},{"subid":"33","name":"E"}]}];

const result = _.uniqBy(_.flatMap(myArray, 'subdata'), 'subid');

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

使用lodash / fp,您可以使用_.flow()通过相同的方法来生成函数:

const fn = _.flow(
  _.flatMap('subdata'),
  _.uniqBy('subid')
);

const myArray = [{"_id":"1","subdata":[{"subid":"11","name":"A"},{"subid":"12","name":"B"}]},{"_id":"2","subdata":[{"subid":"12","name":"B"},{"subid":"33","name":"E"}]}];

const result = fn(myArray);

console.log(result);
<script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>