如何在没有索引的情况下重新排列对象数组中的项目

问题描述

我有一个这种格式的对象数组

sampleItemDetail: [
    {
      type: 'Take out the garbage',isBox1: true
    },{
      type: 'Watch my favorite show',{
      type: 'Charge my phone',isBox2: true
    },{
      type: 'Cook dinner',{
      type: 'Take out the garbage1',{
      type: 'Watch my favorite show2',{
      type: 'Charge my phone3',isBox1: true
    }
]

我正在使用react-beautiful-dnd拖放此对象数组。我也希望能够基于拖放以及isBox标志来分配索引。 什么是最有效的方法。我很困惑,因为状态没有索引。我需要在元素上添加索引属性以实现这种情况吗?

https://codesandbox.io/s/react-beautiful-dnd-tutorial-forked-ij1oq?file=/src/index.js

解决方法

您可以假设items数组的大小始终为3:

// 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,selectedItem);

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