Javascript - 根据常用值重构对象数组

时间:2018-03-01 09:47:49

标签: javascript arrays lodash

我输入的对象数组就像这样,我有一个如下所示的输入数组:

[{"id": 657, "name": "Amadeus Basin", "contenttype": "province"}
{"id": 1173, "name": "Amazonas Basin", "contenttype": "province"}
{"id": 373, "name": "American Samoa", "contenttype": "countries"}
{"id": 1, "name": "Samoa", "contenttype": "marine"}
{"id": 796, "name": "Amhara", "contenttype": "province"}]

我希望实现的目标是:

[
    {
    "contenttype": "province",
    "content" : [
        {
            "id": 657,
            "name": "Amadeus Basin"
        },
        {
            "id": 1173,
            "name": "Amazonas Basin"
        },
        {
            "id": 796,
            "name": "Amhara"
        }
    ]
    }, {

        "contenttype": "countries",
        "content": [
            {
                "id": 373,
                "name" : "American Samoa"
            }
        ]

    },
    {
        "contenttype": "countries",
        "content": [
        {
            "id": 1,
            "name" : "Samoa"
        }
    ]

    }

]

根据一个值拆分数组中的对象,并在这些新创建的对象中创建相同对象的子数组。 使用lodash也不错。

2 个答案:

答案 0 :(得分:2)

您可以使用error 500函数迭代每个项目,然后检查它是否存在于数组中,如果没有找到则添加新项目,如果找到 - 推入它

reduce

答案 1 :(得分:1)

您可以使用_.groupBy并映射所需的属性。

var data = [{ id: 657, name: "Amadeus Basin", contenttype: "province" }, { id: 1173, name: "Amazonas Basin", contenttype: "province" }, { id: 373, name: "American Samoa", contenttype: "countries" }, { id: 1, name: "Samoa", contenttype: "marine" }, { id: 796, name: "Amhara", contenttype: "province" }],
    result = _(data)
        .groupBy('contenttype')
        .map((value, key) => ({
            contenttype: key,
            content: _.map(value, v => _.pick(v, ['id', 'name']))
        }))
        .value();

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