how to compare a string with object value

Viewed 70

I have one object I want to compare that key value with string yes or no I am trying to reach it but that is not working correctly need to compare that and then the radio button will get checked with accordingly yes or no need to handing change with that also.

const screenJson = {
  Management: "yes",
  Configuration: "no",
  Rule: "no",
  Initiate: "yes",
  DM: "no",
  Download: "yes",
  Dashboard: "no",
}
const [selectedValue, setSelectedValue] = React.useState(screenJson);
// ...
  const handleChange = (event) => {
    const copyOfModuleSubModules = _.cloneDeep(selectedValue);
    Object.keys(copyOfModuleSubModules[event.target.name]).forEach((item) => {
      console.log(copyOfModuleSubModules[event.target.name]);
      console.log('dd', event?.target?.value);
      copyOfModuleSubModules[event.target.name][item] = event?.target?.value;
    });
    setSelectedValue({
      ..._.cloneDeep(copyOfModuleSubModules),
    });
  };
<>
  {
    Object.keys(screenJson)?.map((data, index) => (
      <Grid item key={index} mt={2} xs={12} container>
        <Grid item xs={6} mt={2} textAlign="left">
          <Typography variant="body1">{data}</Typography>
        </Grid>
        <Grid item xs={3}>
          {JSON.stringify(
            Object.values(screenJson)
              .filter(data => data)
              .toString() === "yes"
          )}
          <Radio
            checked={
              Object.values(screenJson)
                .filter(data => data)
                .toString() === "yes"
            }
            onChange={handleChange}
            value="a"
            name={data}
            inputProps={{ "aria-label": "A" }}
          />
        </Grid>
        <Grid item xs={3}>
          <Radio
            checked={screenJson?.[Object.keys(screenJson)] === "no"}
             onChange={handleChange}
            value="b"
            name={data}
            inputProps={{ "aria-label": "A" }}
          />
        </Grid>
      </Grid>
    ))
  }
</>

3 Answers

Use this to evaluate if checked is true or false

screenJson[data] === "yes"
or
screenJson[data] === "no"

Complete

{Object.keys(screenJson)?.map((data, index) => (
  <Grid item key={index} mt={2} xs={12} container>
    <Grid item xs={6} mt={2} textAlign="left">
      <Typography variant="body1">{data}</Typography>
    </Grid>
    <Grid item xs={3}>
      {JSON.stringify(
        Object.values(screenJson)
          .filter((data) => data)
          .toString() === 'YES'
      )}
      <Radio
        checked={
          screenJson[data] === "yes"
        }
        // onChange={handleChange(index)}
        value="a"
        name="radio-buttons"
        inputProps={{ 'aria-label': 'A' }}
      />
    </Grid>
    <Grid item xs={3}>
      <Radio
        checked={
          screenJson[data] === "no"
        }
        // onChange={handleChange}
        value="b"
        name="radio-buttons"
        inputProps={{ 'aria-label': 'A' }}
      />
    </Grid>
  </Grid>
))}

UPDATE: In order to make the changes to the state you need to create a reducer and a context so you ca dispatch events to do so. It's a little more complex but basically you can copy paste the code below in the App.js and figure what's happening

  import React, {useContext, useReducer} from 'react'
  import { Radio, Grid, Typography } from '@mui/material'

  //CREATE A REDUCER THAT WILL DISPATCH THE MODIFIED OBJECT
  const reducer = (state, action) => {    
    //Dispatch the event for the checkbox click
    if (action.type === "HANDLE_CHANGE") {
      var output = {...state};
      output[action.payload.key] = action.payload.val
      return output
    }
    throw new Error(`No Matching "${action.type}" - action type`)
  }

  //CREATE A CONTEXT FOR THE REDUCER THAT WILL HANDLE THE STATE DATA
  const DataContext = React.createContext()
  const initialState = {
    Management: "yes",
    Configuration: "no",
    Rule: "no",
    Initiate: "yes",
    DM: "no",
    Download: "yes",
    Dashboard: "no",
  }
  
  // CREATE THE DATA PROVIDER THAT WILL WRAP THE APP OR COMPONENT TO USE THE CONTEXT
  const DataProvider = ({ children }) => {
    //Initialize the state and reducer to be enable for all childrens
    const [state, dispatch] = useReducer(reducer, initialState)
    //Add events that will modify the state using the reducer
    const handleChange = (key, val)=>{
      console.log("handler")
      console.log(key, val)
      dispatch({ type: "HANDLE_CHANGE", payload: {key, val} })
    }
    //Component will include the children being this the App
    //or the main component using the states
    return(
      <DataContext.Provider value={{state, handleChange}} >
        {children}
      </DataContext.Provider>
    )
  }
  //MAIN APP OR TOP COMPONENT
  function App() {
    //Provider is included here so that state and reducer is available
    //for all child components
    return <DataProvider>
      <MainComponent />
    </DataProvider>
  }
  //Your Component that will show the Grid 
  const MainComponent = () => {
    //Pulling state and event handler from the context to use
    const {state, handleChange} = useContext(DataContext)
    return (
      <>
      {
        Object.keys(state)?.map((data, index) => (
          <Grid item key={index} mt={2} xs={12} container>
            <Grid item xs={6} mt={2} textAlign="left">
              <Typography variant="body1">{data}</Typography>
            </Grid>
            <Grid item xs={3}>
              Yes
              <Radio
                checked={state[data] === "yes"}
                onChange={(e)=>handleChange(data, "yes")}
                value="a"
                name={data}
                inputProps={{ "aria-label": "A" }}
              />
            </Grid>
            <Grid item xs={3}>
              No
              <Radio
                checked={state[data] === "no"}
                onChange={(e)=>handleChange(data, "no")}
                value="b"
                name={data}
                inputProps={{ "aria-label": "A" }}
              />
            </Grid>
          </Grid>
        ))
      }
    </>
    )
  }
  
  export default App

Here is a working example for your question.!!

  const screenJson = {
  Management: "yes",
  Configuration: "no",
  Rule: "no",
  Initiate: "yes",
  Initial: "no",
  Download: "yes",
  Dashboard: "no",
}

export default function App() {
  const handleChange = () => {
    console.log('hello');
  }
  return (
    <div className="App">
    
    {
    Object.keys(screenJson)?.map((data, index) => (
      <Grid item key={index} mt={2} xs={12} container>
        <Grid item xs={6} mt={2} textAlign="left">
          <Typography variant="body1">{data}</Typography>
        </Grid>
        <Grid item xs={3}>
          {screenJson[data] === 'yes' ? 'true' : 'false'}
          {/* {JSON.stringify(
            Object.values(screenJson)
              .filter(data => data)
              .toString() === "yes"
          )} */}
          <Radio
            checked={
              screenJson[data] === 'yes'
            }
            onChange={handleChange(index)}
            value="a"
            name="radio-buttons"
            inputProps={{ "aria-label": "A" }}
          />
        </Grid>
        <Grid item xs={3}>
          <Radio
            checked={screenJson?.[Object.keys(screenJson)] === "no"}
            // onChange={handleChange}
            value="b"
            name="radio-buttons"
            inputProps={{ "aria-label": "A" }}
          />
        </Grid>
      </Grid>
    ))
  }
    </div>
  );
}

Try

Object.keys(screenJson).map(data=> {
    <Radio
        checked={
          screenJson[data]==='yes'
        }
        value="a"
        ...
     />

    <Radio
        checked={
          screenJson[data]==='no'
        }
        value="b"
        ...
     />

}
Related