数组操作 - lodash 或 underscore js

Array manipulation - lodash or underscore js

我需要更改 lodash 或下划线数组的格式:

[
    {
        name: "john",
        type: "facebook"
    },
    {
        name: "Mike",
        type: "facebook"
    },
    {
        name: "Jacob",
        type: "twitter"
    },
    {
        name: "Nancy",
        type: "twitter"
    },
    {
        name: "Antony",
        type: "facebook"
    },
    {
        name: "Viki",
        type: "linkedin"
    }
]

需要将上面的数组转为对象,如下

{
    facebook: [
        {
            name: "john",
            type: "facebook"
        },
        {
            name: "Mike",
            type: "facebook"
        },
         {
            name: "Antony",
            type: "facebook"
        }
    ],
    twitter: [
         {
            name: "Jacob",
            type: "twitter"
        },
        {
            name: "Nancy",
            type: "twitter"
        }
    ],
    linkedin: [
        {
            name: "Viki",
            type: "linkedin"
        }
    ] 
}

我试过 groupBy 功能,但它对我不起作用。所以我没有太多示例代码可以展示。如果有人帮我找到解决方案,那将是很大的帮助。谢谢你。

你可以试试这个:

function manipulate(yourArray) {
  var res = {}
  for (var i=0; i<yourArray.length; i++) {
    if (!res.hasOwnProperty(yourArray[i].type)){
      res[yourArray[i].type] = []
    }
    res[yourArray[i].type].push(yourArray[i])
  }
  return res;
}

您应该使用 groupBy() 重新访问。我刚刚在你的输入样本上试过它,它产生了你想要的确切输出:

_.groupBy(array, 'type');