gpt4 book ai didi

javascript - 按嵌套对象数组中的属性值对对象数组进行排序

转载 作者:行者123 更新时间:2023-12-02 18:29:10 25 4
gpt4 key购买 nike

我试图弄清楚如何根据嵌套对象数组中的属性值是否包含值 stopped 对对象数组进行排序。当该值存在于任何嵌套的对象数组中时,我需要将父对象排序到顶部,从那里,我尝试按 id 对排序列表进行二次排序。

const arr = [{
id: 1,
things: [{
thing_id: 1,
status: 'started',
},
{
thing_id: 1,
status: 'started',
},
],
},
{
id: 2,
things: [{
thing_id: 1,
status: 'started',
},
{
thing_id: 1,
status: 'started',
},
{
thing_id: 1,
status: 'stopped',
},
],
},
{
id: 3,
things: [{
thing_id: 1,
status: 'started',
},
{
thing_id: 1,
status: 'started',
},
{
thing_id: 1,
status: 'started',
},
{
thing_id: 1,
status: 'started',
},
],
}
]

// desired result
[{
id: 2,
things: [{
thing_id: 1,
status: 'started',
},
{
thing_id: 1,
status: 'started',
},
{
thing_id: 1,
status: 'stopped',
},
],
},
{
id: 1,
things: [{
thing_id: 1,
status: 'started',
},
{
thing_id: 1,
status: 'started',
},
],
},
{
id: 3,
things: [{
thing_id: 1,
status: 'started',
},
{
thing_id: 1,
status: 'started',
},
{
thing_id: 1,
status: 'started',
},
{
thing_id: 1,
status: 'started',
},
],
}
]

最佳答案

const checkStopped = (things) => things.some((el) => el.status === 'stopped');

const desired = arr.sort((a, b) => checkStopped(b.things) - checkStopped(a.things));

关于javascript - 按嵌套对象数组中的属性值对对象数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69667938/

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