Modifying an array of objects with uuid keys

I've got add

I've got delete

now I need modify

add just adds to the pile haphazardly

delete is able to do it's work with surgical precision because it uses key to find it's culprit :

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);
};

how do I modify (for example set the value back to '' without deleting and recreating the item) ?

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

Answers:

Answer

You can use Array.prototype.find()

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

You can map through the parameters and then modify when you find a match:

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);
};
Answer
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;

    }

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.