I have a complicated array of objects and I want to change a property that deeply nested in the array.
I did the following function and it is work, but the problem is that the eslint throw me an error because there is a nested ternery to check if i am on the currect place in an array:
toggleSwitchDetector(state: Array<IOpticalHeadUnit>, { payload }: any) {
return [
...state.map((opticalHeadUnit) =>
opticalHeadUnit.name === payload.opticalHeadUnitName
? {
...opticalHeadUnit,
detectors: [
...opticalHeadUnit.detectors.map(
(detector, index) => ({
...detector,
status: {
...detector.status,
value: //Nested ternery. Bad practice.
index === payload.index
? detector.status
.value === 0
? 1
: 0
: detector.status.value,
},
}),
),
],
}
: opticalHeadUnit,
),
];
}
is there a simpler way to approach the modification of the deeply nested property?
EDIT:
the code after I modified it with the answers:
const getDetectorStatusValue=(index:number,payload:number,detector:IDetector)=>{
if(index === payload)
{
if(detector.status.value===0)
return 1
return 0
}
return detector.status.value
}
toggleSwitchDetector(state: Array<IOpticalHeadUnit>, { payload }: any) {
return state.map((opticalHeadUnit) =>
opticalHeadUnit.name === payload.opticalHeadUnitName
? {
...opticalHeadUnit,
detectors: [
...opticalHeadUnit.detectors.map(
(detector,index) => ({
...detector,
status: {
...detector.status,
value:getDetectorStatusValue(index,payload.index,detector)
},
}),
),
],
}
: opticalHeadUnit,
);
If you want to get rid of the nested ternary operator, you could write slightly more code but it will be more readable.
You can check if index === payload.index with a simple if statement and only in that case go deep in your object to eventually check detector.status.value === 0 ? 1 : 0
Otherwise just return detector as is;
...opticalHeadUnit.detectors.map(
(detector, index) => ({
if (index === payload.index) {
return {
...detector,
status: {
...detector.status,
value: detector.status.value === 0 ? 1 : 0
},
}
} else {
return detector;
}
}),
),
Maybe something like this
toggleSwitchDetector(state: Array<IOpticalHeadUnit>, { payload }: any) {
return state.map((opticalHeadUnit) => getState(payload, opticalHeadUnit)
}
getStatus(payload, detector) {
return {
...detector.status,
value: //Nested ternery. Bad practice.
index === payload.index
? detector.status
.value === 0
? 1
: 0
: detector.status.value,
};
}
getDetectors(payload, opticalHeadUnit) {
return opticalHeadUnit.detectors.map(
(detector, index) => ({
...detector,
status: getStatus(payload, detector),
}),
);
}
getState(payload, opticalHeadUnit) {
opticalHeadUnit.name === payload.opticalHeadUnitName
? {
...opticalHeadUnit,
detectors: getDetectors(payload, opticalHeadUnit);
}
: opticalHeadUnit,
}
you don't need [...array], replace it with array