0

I'm trying to update a specific value based on the id in a data array. I'm trying to do this inside my reducer in redux.

For example what i need is something like this

            case STATION_SELECT:
            const checkedGroupData = (data,id) => {
                    console.log(data);
                    console.log(id);
            }

            return {
                ...state,
                chargingStationGroups: Object.values(checkedGroupData(state.chargingStationGroups,action.id)),
            }

So here console.log value for data is like below

[
  0: 
     groupId: "31"
     groupName: "Test"
     stations: [
       0: {stationID: "26",name: "TestName",checked:false}
       1: {stationID: "28",name: "TestName2",checked:false}
     ]
  1: 
     groupId: "32"
     groupName: "Test332"
     stations: [
       0: {stationID: "29",name: "TestName1212",checked:false}
       1: {stationID: "30",name: "TestName122",checked:false}
     ]

]

so if my console.log for id is 26 how can i change the checked:false to checked:true for stationID: 26

1 Answer 1

1

You can use nested Array.map and check for stationID if it matches the id return true, if not, return the original one :

const checkedGroupData = (data, id) => {
  return data.map(o => ({
    ...o,
    stations: o.stations.map(s => ({
      ...s,
      checked: s.stationID === id ? true : s.checked
    }))
  }));
};

const data = [
  {
    groupId: "31",
    groupName: "Test",
    stations: [
      { stationID: "26", name: "TestName", checked: false },
      { stationID: "28", name: "TestName2", checked: false }
    ]
  },
  {
    groupId: "32",
    groupName: "Test332",
    stations: [
      { stationID: "29", name: "TestName1212", checked: false },
      { stationID: "30", name: "TestName122", checked: false }
    ]
  }
];

const result = checkedGroupData(data, "26");

console.log(result);

Sign up to request clarification or add additional context in comments.

4 Comments

This sets the Boolean property checked to the string value of stationID, which seems... odd. Wouldn't it be better to use checked: s.stationID === id?
Although this solution changes the checked status, it does not hold the checked status. When i click on another checkbox, that particular checkbox gets checked and the other checkbox will uncheck. How can i handle this?
@HereticMonkey my bad, i guess i wrote it too fast, i fixed it, i think checked: s.stationID === id can override the checked to false on all the other objects that doesn't match the id and might have checked:true, i prefere to keep the original value.
@CraZyDroiD try the updated the answer, it had a mistake in it,

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.