【问题标题】:Modifying an array of objects with uuid keys使用 uuid 键修改对象数组
【发布时间】:2018-03-24 16:29:09
【问题描述】:

我已经添加了

我已经删除了

现在我需要修改

添加只是随意添加到堆中

delete 能够以外科手术般的精确度完成它的工作,因为它使用密钥来找到它的罪魁祸首:

addInput = (name) => {
    const newInputs = this.props.parameters;
    newInputs.push({
        name,
        key: uuid(),
        value: { input: '' },
        icon: { inputIcon: 0 },
    });
    this.setState({
        newInput: newInputs,
    });
    this.props.exportParameter(newInputs);
};

removeInput = (key) => {
    const newInputs = this.props.parameters.filter(x => x.key !== key);
    this.setState({
        newInput: newInputs,
    });
    this.props.exportParameter(newInputs);
};

如何修改(例如将值设置回 '' 而不删除并重新创建项目)?

modifyInput = (key) => {
    ?????
};

【问题讨论】:

    标签: javascript arrays reactjs react-native


    【解决方案1】:

    您可以使用Array.prototype.find()

    modifyInput = (key) => {
      const match = this.props.parameters.find(x => x.key === key);
      // do stuff with matched object
    };
    

    【讨论】:

      【解决方案2】:

      你可以通过参数map找到匹配的时候再修改:

      modifyInput = (key) => {   
          const newInputs = this.props.parameters.map(x => {
              if (x.key === key) {
                 x.modification = true;
              }
              return x;
          });
          this.setState({
              newInput: newInputs,
          });
          this.props.exportParameter(newInputs);
      };
      

      【讨论】:

      • "不删除并重新创建项目)"
      • 是的。这也没有?
      【解决方案3】:
      var empMap= {};
          //initialize empMap with key as Employee ID and value as Employee attributes:
          //Now when salary updated on UI from 100 - 300 you can update other fields 
          var e=empMap[id];
          if(e){
              e.Salary=newSalary;
              e.YearlySalary = newSalary*12;
              e.Deductions = e.YearlySalary*0.2;
              empMap[id]=e;
      
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-09-28
        • 2022-07-07
        • 1970-01-01
        • 2020-01-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多