tatsu
tatsu

Reputation: 2536

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

Upvotes: 1

Views: 1421

Answers (3)

Chandrakant
Chandrakant

Reputation: 11

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;

    }

Upvotes: 1

Davin Tryon
Davin Tryon

Reputation: 67296

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

Upvotes: 1

guest271314
guest271314

Reputation: 1

You can use Array.prototype.find()

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

Upvotes: 3

Related Questions