gpt4 book ai didi

javascript - 如何在更改键后移动数组中的对象

转载 作者:行者123 更新时间:2023-11-29 19:10:55 25 4
gpt4 key购买 nike

我有一个数组,其中的对象按“order”键排序

[
{order: 1, id: 1, title: elem1},
{order: 2, id: 2, title: elem2},
{order: 3, id: 3, title: elem3},
{order: 4, id: 4, title: elem4},
{order: 5, id: 5, title: elem5}
]

将“elem2”中的键“order”更改为“4”后,数组应如下所示

[
{order: 1, id: 1, title: elem1},
{order: 2, id: 3, title: elem3},
{order: 3, id: 4, title: elem4},
{order: 4, id: 2, title: elem2},
{order: 5, id: 5, title: elem5}
]

我想在双向更改某些对象中的键“顺序”后移动数组中的对象

最佳答案

您可以使用 Array.prototype.sort()功能:

var elem1, elem2, elem3, elem4, elem5;
var arr = [
{order: 1, id: 1, title: elem1},
{order: 2, id: 2, title: elem2},
{order: 3, id: 3, title: elem3},
{order: 4, id: 4, title: elem4},
{order: 5, id: 5, title: elem5}
];

arr[1].order = 4;
arr[3].order = 2;

arr.sort((a, b) => a.order > b.order);

关于javascript - 如何在更改键后移动数组中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38882833/

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