gpt4 book ai didi

javascript - 根据属性值对对象进行排序

转载 作者:行者123 更新时间:2023-11-30 09:33:05 26 4
gpt4 key购买 nike

我有对象数组,我怎样才能搜索所有对象并根据属性值对它们进行分类

 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}]

我试过使用find在 lodash 中不断变得不确定

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

最佳答案

您可以使用 _.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>

请注意 weekGroups 是一个 Object 而不是 Array

关于javascript - 根据属性值对对象进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45157587/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com