如何将对象数组拆分为某些属性的相同值连接的对象数组?

时间:2018-04-12 17:47:06

标签: javascript

所以我有这个对象数组:

var users =
 [ 
  { action: 'search', time: 1487098109, name: 'Charlie' },
  { action: 'search', time: 1487184715, name: 'Charlie' },
  { action: 'search', time: 1487184755, name: 'John' },
  { action: 'search', time: 1487271527, name: 'John' },
  { action: 'search', time: 1487271527, name: 'Mark' },
  { action: 'search', time: 1487271537, name: 'Mark' },
  { action: 'c', time: 1487098139, name: 'Mike' },
  { action: 'b', time: 1487098169, name: 'Mike' },
  { action: 'a', time: 1487098199, name: 'Mike' },
  { action: 'login', time: 1487098300, name: 'Mike' },
  { action: 'search', time: 1, name: 'Robert' },
  { action: 'search', time: 2, name: 'Robert' },
  { action: 'search', time: 1487098169, name: 'Woody' },
  { action: 'search', time: 1487271467, name: 'Woody' } 
 ]

我想将它转换为这个结构,这是一个由同名属性连接的对象数组数组:

[
  [
    { action: 'search', time: 1487098109, name: 'Charlie' },
    { action: 'search', time: 1487184715, name: 'Charlie' }
  ],
  [
    { action: 'search', time: 1487184755, name: 'John' },
    { action: 'search', time: 1487271527, name: 'John' }
  ],
  [
    { action: 'search', time: 1487271527, name: 'Mark' },
    { action: 'search', time: 1487271537, name: 'Mark' }
  ],
  [
    { action: 'c', time: 1487098139, name: 'Mike' },
    { action: 'b', time: 1487098169, name: 'Mike' },
    { action: 'a', time: 1487098199, name: 'Mike' },
    { action: 'login', time: 1487098300, name: 'Mike' }
  ],
  [
    { action: 'search', time: 1, name: 'Robert' },
    { action: 'search', time: 2, name: 'Robert' }
  ],
  [
    { action: 'search', time: 1487098169, name: 'Woody' },
    { action: 'search', time: 1487271467, name: 'Woody' }
  ]
]

那我怎么能做到这一点?提前谢谢!

1 个答案:

答案 0 :(得分:1)

您可以排序然后执行函数reduce以按名称对对象进行分组。



var users = [   { action: 'search', time: 1487098109, name: 'Charlie' },  { action: 'search', time: 1487184715, name: 'Charlie' },  { action: 'search', time: 1487184755, name: 'John' },  { action: 'search', time: 1487271527, name: 'John' },  { action: 'search', time: 1487271527, name: 'Mark' },  { action: 'search', time: 1487271537, name: 'Mark' },  { action: 'c', time: 1487098139, name: 'Mike' },  { action: 'b', time: 1487098169, name: 'Mike' },  { action: 'a', time: 1487098199, name: 'Mike' },  { action: 'login', time: 1487098300, name: 'Mike' },  { action: 'search', time: 1, name: 'Robert' },  { action: 'search', time: 2, name: 'Robert' },  { action: 'search', time: 1487098169, name: 'Woody' },  { action: 'search', time: 1487271467, name: 'Woody' }  ];

var result = Object.values(users.sort((a, b) => a.name.localeCompare(b.name)).reduce((a, c) => {
  (a[c.name] || (a[c.name] = [])).push(c);
  return a;
}, {}));

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }