如何将对象数组分别分成单个对象

时间:2018-01-31 19:00:52

标签: javascript arrays lodash

我正在使用lodash对一组对象进行分组:

let people = [{name:'carl',group:'one'}, 
{name:'john',group:'one'}, 
{name:'dean',group:'three'}]
_.groupBy(people,"group");

结果:

one: Array (2 items)
0: Object {group: "one", name: "carl"}
1: Object {group: "one", name: "john"}

three: Array (1 item)
0: Object {group: "three", name: "dean"}

我想要的是组数组长度大于1的对象,以便单独分成另一个数组:

one: Array (1 item)
0: Object {group: "one", name: "carl"}

one: Array (1 item)
0: Object {group: "one", name: "john"}

three: Array (1 item)
0: Object {group: "three", name: "dean"}

最好的方法是什么?

1 个答案:

答案 0 :(得分:0)

我认为你可以使用“排序”方法

let people = [{name:'carl',group:'one'}, 
 {name:'john',group:'one'}, 
 {name:'dean',group:'three'}];

people.sort(function(a,b){
  return a.name.localeCompare(b.name)
});

参考: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort