javascript - 重新排序对象数组

标签 javascript reactjs

在我的 React 状态下,我想通过始终将选定的对象放在中间,同时保持其他对象按升序排列,对 3 个对象的数组进行重新排序。

现在,我在每个对象中使用 order 属性来跟踪顺序,但这可能不是最好的方法。

例如:

this.state = {
  selected: 'item1',
  items: [
    {
      id: 'item1',
      order: 2
    },
    {
      id: 'item2'
      order: 1
    },
    {
      id: 'item3'
      order: 3
    }
  ]
}

Resulting array : [item2, item1, item3]

现在,假设用户选择item2。我将相应地更新 selected 状态属性,但如何更新 items 属性以最终得到如下结果:

this.state = {
  selected: 'item2',
  items: [
    {
      id: 'item1',
      order: 1
    },
    {
      id: 'item2'
      order: 2
    },
    {
      id: 'item3'
      order: 3
    }
  ]
}

Resulting array : [item1, item2, item3]

你会怎么做?我已经看到一些 lodash 实用函数可以提供帮助,但我想用普通 JavaScript 来完成此任务。

最佳答案

你可以做一些像这样的粗暴的事情:

// Create a local shallow copy of the state
var items = this.state.items.slice()

// Find the index of the selected item within the current items array.
var selectedItemName = this.state.selected;
function isSelectedItem(element, index, array) {
    return element.id === selectedItemName;
};
var selectedIdx = items.findIndex(isSelectedItem);

// Extract that item
var selectedItem = items[selectedIdx];

// Delete the item from the items array
items.splice(selectedIdx, 1);

// Sort the items that are left over
items.sort(function(a, b) {
    return a.id < b.id ? -1 : 1;
});

// Insert the selected item back into the array
items.splice(1, 0, selectedItem);

// Set the state to the new array
this.setState({items: items});

这假设 items 数组的大小始终为 3!

关于javascript - 重新排序对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44294634/

相关文章:

javascript - 编写 .d.ts 文件以便我可以与 JavaScript 和 TypeScript 共享常量?

javascript - 如何从 AngularJS Bootstrap 模式中的 AJAX 调用加载 JSON 数据

Javascript 语法 - 类的箭头函数

javascript - 如何在 React Native 中重用 React JS 组件

html - 为什么省略 0ms sleep 会破坏我的 css 转换?

javascript - setState 对象数组而不改变对象顺序

javascript - Nullish 合并运算符不工作或未启用?

javascript - 如何将 JSON 字符串转换为具有不同结构的 JSON 字符串

javascript - 只允许特定的 URL 访问我的网站

css - Material ui 选项卡容器的动态高度