使用uuid键修改对象数组

时间:2017-10-12 16:29:39

标签: javascript arrays reactjs react-native

我已经添加了

我已删除

现在我需要修改

添加只是偶然添加到堆中

删除能够做到手术精确,因为它使用密钥来找到它的罪魁祸首:

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) => {
    ?????
};

3 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:1)

您可以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);
};

答案 2 :(得分:1)

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;

    }