在我的 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/