根据属性值对对象排序

时间:2017-07-18 04:36:45

标签: javascript lodash

我有对象数组,如何搜索所有对象并根据属性值对其进行分类

 data = [ 
  {key: 1, val: Mon, week: 0},
  {key: 1, val: Wed, week: 0},
  {key: 1, val: Mon, week: 1},
  {key: 1, val: Mon, week: 1}
  {key: 1, val: Mon, week: 2}
]

期望的输出

week0Array = [{key: 1, val: Mon, week: 0},{key: 1, val: Wed, week: 0}]
week1Array = [{key: 1, val: Mon, week: 1}, {key: 1, val: Mon, week: 1} ]
week2Array = [{key: 1, val: Mon, week: 2}]

我试图在lodash中使用find并保持未定义

_.find(collection, [predicate=_.identity], [fromIndex=0])

2 个答案:

答案 0 :(得分:3)

您可以像这样使用_.groupBy(collection, [iteratee=_.identity])



let data = [ 
  {key: 1, val: 'Mon', week: 0},
  {key: 1, val: 'Wed', week: 0},
  {key: 1, val: 'Mon', week: 1},
  {key: 1, val: 'Mon', week: 1},
  {key: 1, val: 'Mon', week: 2}
]

let weekGroups = _.groupBy(data, d => d.week)

console.log(weekGroups[0])
console.log(weekGroups[1])
console.log(weekGroups[2])

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
&#13;
&#13;
&#13;

请注意,weekGroupsObject而不是Array

答案 1 :(得分:1)

正如POJS替代方案并假设数据按开始排序,reduce可以创建一个数组,其中的对象按周分组为子数组。如果需要排序,可以在调用reduce之前添加:

&#13;
&#13;
var data = [ 
    {key: 1, val: "Mon", week: 0},
    {key: 1, val: "Wed", week: 0},
    {key: 1, val: "Mon", week: 1},
    {key: 1, val: "Mon", week: 1},
    {key: 1, val: "Mon", week: 2}
];

var result = data.reduce((acc, obj, i) => {
    i && acc[acc.length-1].week == obj.week ?
        acc[acc.length-1].push(obj) :
        acc.push([obj]);

    return acc;
}, []);

console.log(result)
&#13;
&#13;
&#13;

条件? :中的括号不是必需的,但我认为它们有助于提高可读性。