Home > Mobile >  Filtering Json data based on key and assiging the value to state in react
Filtering Json data based on key and assiging the value to state in react

Time:09-30

I'm trying to hit the backend call and I get the below JSON data. I've to filter based the key which value starts with "CD_".

After that I've to assign "CD_type" and "CD_name" to two different state from which I'll iterate and show the "name" value in two dropdowns.

JSON

   var data = {
        "color": "red",
        "value": "#f00",
        "response": [{
                "code": "CD_type",
                "name": "sampleText_1"
            },
            {
                "code": "RS_type",
                "name": "sampleText_1"
            },
            {
                "code": "AD_name",
                "name": "sampleText_1"
            },
            {
                "code": "RS_type",
                "name": "sampleText_1"
            },
            {
                "code": "AD_name",
                "name": "sampleText_1"
            },
            {
                "code": "CD_name",
                "name": "sampleText_1"
            }, {
                "code": "CD_name",
                "name": "sampleText_1"
            },
            {
                "code": "RS_type",
                "name": "sampleText_1"
            },
            {
                "code": "AD_name",
                "name": "sampleText_1"
            },
            {
                "code": "CD_type",
                "name": "sampleText_2"
            },
            {
                "code": "CD_type",
                "name": "sampleText_3"
            }, {
                "code": "CD_name",
                "name": "sampleText_2"
            },
            {
                "code": "RS_type",
                "name": "sampleText_1"
            },
            {
                "code": "AD_name",
                "name": "sampleText_1"
            },
            {
                "code": "CD_name",
                "name": "sampleText_1"
            },
            {
                "code": "CD_name",
                "name": "sampleText_1"
            },
            {
                "code": "CD_type",
                "name": "sampleText_4"
            },
            {
                "code": "CD_name",
                "name": "sampleText_3"
            },
            {
                "code": "CD_type",
                "name": "sampleText_5"
            }
        ]
}

JS:

const [cdValue,setCdValue] = useState([]);

const data = data.filter(item => {
   setCdValue(item.code.startsWith("CD_"))
  return item.code.startsWith("CD_")
});

Its throwing promise is waiting when I consoled.

CodePudding user response:

You have to first filter the items. The result is a filtered list of items. And only after that call setCdValue with that filtered list:

setCdValue(data.filter(item => item.code.startsWith("CD_")));
  • Related