https://codesandbox.io/s/polished-bird-662mh?from-embed
我有一个对象数组和一个具有以下结构的对象
this.state = {
arr : [ {
id: "val1",
initialVal: "test1",
finalVal: "final1"
},
{
id: "val2",
initialVal: "test2",
finalVal: "final2"
},
{
id: "val3",
initialVal: "test3",
finalVal: "final3"
},
{
id: "val4",
initialVal: "test4",
finalVal: "final4"
}
],
values: [ "test1","test3"]
}
this.obj = { field: "test1" , val:6}
我正在编写一个函数,该函数将这个 obj 作为其参数,并根据“字段”值,它应该使用 obj 的“val”属性设置“finalVal”的状态,并进行以下计算(如果 val 大于 5,则添加“ ok”到该字段,否则添加“cancel”)并且属性在状态的“values”数组中不匹配的对象应将其“finalVal”设置为空白
所以输出应该照顾设置状态:
[
{
id: "val1",
initialVal: "test1",
finalVal: "ok"
},
{
id: "val2",
initialVal: "test2"
finalVal: "final2"
},
{
id: "val3",
initialVal: "test3"
finalVal: ""
},
{
id: "val4",
initialVal: "test4"
finalVal: "final4"
}
]
//What I have tried so far
setObjState = obj => {
let arr = [...this.state.arr];
let finalArr = arr.map(function(item) {
if (item.initialVal === obj.field) {
return { ...item, finalVal: obj.val > 5 ? "Ok" : "Cancel" };
} else {
if(this.state.values.includes(item.id){
return { ...item, finalVal: "" };
}
}
});
console.log(finalArr);
this.setState({ arr: finalArr });
}
相关分类