过滤唯一字段并从对象数组推入数组

时间:2018-06-29 18:57:09

标签: javascript arrays json node.js function

我想要以下解决方案,我尝试使用下划线,groupBy,但是它返回的是数组内具有唯一名称的数组对象,但是我不想要该解决方案,我想要下面所示的内容 如何转换:

[
    {food: 'apple', type: 'fruit'},
    {food: 'potato', type: 'vegetable'},
    {food: 'apple', type: 'fruit'},
    {food: 'apple', type: 'fruit'},
    {food: 'potato', type: 'vegetable'},
]

对此:

[
    [ {food: 'apple', type: 'fruit'}, 
      {food: 'apple', type: 'fruit'}, 
      {food: 'apple', type: 'fruit'}]
    ],
    [ {food: 'potato', type: 'vegetable'}, 
      {food: 'potato', type: 'vegetable'}
    ]
]

使用javascript或下划线, 请通过javascript函数帮助我完成此任务,

2 个答案:

答案 0 :(得分:0)

您可以使用reduce将群组放入地图中,然后获取解构后的values()

const d = [
  {food: 'apple', type: 'fruit'},
  {food: 'potato', type: 'vegetable'},
  {food: 'apple', type: 'fruit'},
  {food: 'apple', type: 'fruit'},
  {food: 'potato', type: 'vegetable'},
];
const groupBy = 'food'; // change to whatever key you want to group by
const res = [...d.reduce((a,b) => a.set(b[groupBy], (a.get(b[groupBy]) || []).concat(b)), new Map).values()];
console.log(res);

答案 1 :(得分:0)

您可以先使用Array.prototype.reduce amd然后映射值

const array = [
    {food: 'apple', type: 'fruit'},
    {food: 'potato', type: 'vegetable'},
    {food: 'apple', type: 'fruit'},
    {food: 'apple', type: 'fruit'},
    {food: 'potato', type: 'vegetable'},
];

let data = array.reduce((prev, curr) => {
  if (curr.food in prev) {
    prev[curr.food].push(curr);
  } else {
    prev[curr.food] = [curr];
  }
  return prev;
}, {});
data = Object.keys(data).map(key => data[key]);
console.log(data);