Javascript按值分组对象

分享于2022年07月17日 arrays javascript json lodash 问答
【问题标题】:Javascript按值分组对象(Javascript group objects by value)
【发布时间】:2022-01-27 00:06:08
【问题描述】:

首先,我需要根据策略属性的值对一组对象进行分组。然后我需要对动作和公司字段进行分组。我尝试使用 lodash 但无法访问嵌套数组。

从此=>

[
    {
        "action": "VIEW",
        "policy": "FORM"
    },
    {
        "action": "CREATE",
        "policy": "USER"
    },
    {
        "action": "VIEW",
        "policy": "USER"
    },
    {
        "company": "Microsoft",
        "policy": "FORM"
    },
    {
        "company": "Facebook",
        "policy": "USER"
    },
    {
        "company": "Twitter",
        "policy": "USER"
    }
]

到这个=>

{
    "FORM": {
            "action": ["VIEW"],
            "company": ["Microsoft"]
        },
    "USER": {
            "action": ["CREATE", "VIEW"],
            "company": ["Facebook", "Twitter"]
        }
}

非常感谢


【解决方案1】:

您可以为此解决方案使用 lodash 库:


const content = {
    "success": 1,
    "data": [
        {
            "clustername": "c2",
            "monthday": "12/29"
        },
        {
            "clustername": "C3",
            "monthday": "12/29"
        },
        {
            "clustername": "C71",
            "monthday": "12/31"
        },
        {
            "clustername": "C34",
            "monthday": "12/31"
        },
        {
            "clustername": "C998",
            "monthday": "1/4"
        },
        {
            "clustername": "C99",
            "monthday": "1/4"
        }
    ]
};
function customName(n) {
  return {name:n.clustername};
}


const array =  _.chain(content.data)
    .groupBy("monthday")
    .map((value, key) => ({ name: key, children:  _.map(value,v => customName(v))
    }))
    .value()
console.log(array);