首页 > 解决方案 > 控制数组中对象的位置

问题描述

我已经在这个问题上工作了几个小时。在这种情况下,我有一个表单,允许用户从一个选择字段中选择多个类。每次用户选择一个新类时,数组都会更新。我在控制数组中对象的位置时遇到了很多麻烦。如果对象变得乱序,则用户屏幕上的选择字段会发生变化,这对用户来说不是很友好。

我已经设法使用下面的代码解决了这个问题,但是,它似乎很复杂。我想知道是否有一种“更好”或“更简单/更清洁”的方式来写我所做的事情。我是一个相当初级的自学成才的程序员。我问这个是因为我想学习。

类数组

classes = [
  {
    classId: 'yP9w2urWSz3Y4kbhN',
    active: true,
  },
  {
    classId: '3x8cNzzr4DQ4PioM7',
    active: false,
  },
];

** 表单类选择字段 **

{this.state.classes.map((myClass) => {
  if (myClass.active) {
    return (
      <div key={myClass.classId} className="mb-3">
            <FormGroup>
              <Input
                type="select"
                name="classId"
                value={myClass.classId}
                onChange={this.handleClassSelect(myClass.classId)}
                id="classId"
              >
                <option>Select class</option>
                {myClass.options.map(eachClass => (
                  <option key={eachClass._id} value={eachClass._id}>{eachClass.name} 1 {eachClass._id}</option>
                ))}
              </Input>
              {(myClass && myClass.classError) ? <FormFeedback>{myClass.classError}</FormFeedback> : null}
            </FormGroup>
        </div>
  })})}

更新表单的代码

let newValueObject = {
  [name]: value,
  active: true,
  activeDate: new Date(),
};
const newClasses = [];

// map over the current array. Update where required and push elements into newClasses array
this.state.classes.map((myClass, index) => {
  if (myClass.classId === value) {
    newClasses.push({
      ...myClass,
      [name]: value,
      active: true,
    });
    newValueObject = {
      ...myClass,
      [name]: value,
      active: true,
    };
  }
  if (myClass.classId === classId && isNaN(myClass.classId)) {
    newClasses.push({
      ...myClass,
      [name]: classId,
      active: false,
    });
  }

  if (myClass.classId !== value && myClass.classId !== classId) {
    newClasses.push({
      ...myClass,
    });
  }
});

// Check to see if value of select field excists in newClass array
const classIdExist = newClasses.some(myClass => myClass.classId === classId);
const valueExist = newClasses.some(myClass => myClass.classId === value);
// Check the index of value
const valueIndex = newClasses.findIndex(myClass => myClass.classId === value);
// Check the index of classId
const classIdIndex = newClasses.findIndex(myClass => myClass.classId === classId);


// If select value or select classId are found in the array
// make sure array is in the correct order. The order will effect the way they
// appear on the client form.
if (classIdExist && valueExist) {
  // fix order of array
  if (classIdIndex > valueIndex) {
    newClasses.splice(classIdIndex, 0, newValueObject);
    newClasses.splice(valueIndex, 1);
  }
  if (classIdIndex < valueIndex) {
    newClasses.splice(valueIndex, 1);
    newClasses.splice(classIdIndex, 0, newValueObject);
  }
} else if (classIdExist && !valueExist) {
  // add new value
  newClasses.splice(classIdIndex, 0, newValueObject);
} else if (!classIdExist && valueExist) {
  // dont do anything, element in the right place in array
} else {
  newClasses.push(newValueObject);
}

console.log('newClasses', newClasses);

标签: javascriptreactjsecmascript-6

解决方案


推荐阅读