Setting A Property Of An Object Inside Array Of Objects Based On A Match: React Js
https://codesandbox.io/s/polished-bird-662mh I am having this an array of objects and an object with the following structure this.state = { arr : [ {
Solution 1:
First thing you need map function to update new state.
You need to fix this only:
setObjState = obj => {
console.log(obj);
let arr = [...this.state.arr];
let finalArr = arr.map(function(item) {
if (item.initialVal === obj.field) {
return { ...item, finalVal: obj.val > 5 ? "Cancel" : "Ok" };
} else {
return { ...item, finalVal: "" };
}
});
console.log(finalArr);
this.setState({ arr: finalArr });
}
Here is full code and demo : https://codesandbox.io/s/nervous-hodgkin-uxhoi
Solution 2:
You should map the array, returing an object and the value of the field you want have a condition to check decide the value;
let filteredArr = arr.map(x => ({...x, finalVal: (x.initialVal == obj.field ? (obj.val > 5 ? "Ok" : "Cancel" ) : "")}))
this.setState({arr: filteredArr})
let obj = { field: "test1" , val: 6}
let arr = [ {
id: "val1",
initialVal: "test1",
finalVal: "final1"
},
{
id: "val2",
initialVal: "test2",
finalVal: "final2"
},
{
id: "val3",
initialVal: "test3",
finalVal: "final3"
}
]
let filteredArr = arr.map(x => ({...x, finalVal: (x.initialVal == obj.field ? (obj.val > 5 ? "Ok" : "Cancel" ) : "")}))
console.log(filteredArr)
Post a Comment for "Setting A Property Of An Object Inside Array Of Objects Based On A Match: React Js"