Search code examples
javascriptreactjsarraysjsonarrayofarrays

Loop through an Array of objects where each object contains an array


I am coding a form which has a Phone Number input (text) and countries input (select). I want to set a box besides my phone number input which contains the prefix code for the country currently chosen.

I am doing this using an array of objects which contains 7 objects (7 continents). Each off these object has a label attribute which has the name of the continent and a options attribute which I am feeding into my countries select. This format is required to use chakra react select. Now the options is an array which in itself contains objects having label attribute which contains name of country, code which contains phone number prefix.

I have a use effect that runs every time I change my country and within it I want to set my phone number prefix state to whichever code attribute I can match with within my groupedCountries object

var groupedCountries=\[
    {
        label:'Asia',
        options:\[
            label: "Afghanistan", value: "Afghanistan", code: "+93" },
            {},...
        ]
    },
    {},{}...
]

I have tried this inside useEffect:

console.log(
  groupedCountries.forEach((continent) => {
    console.log(`/n${continent}/n`)
    continent.options.filter((country) => {
      console.log(country.label===props.data.country);
      return country.label === props.data.country;
    });
  })
);

This gives me in the console-

console screenshot

I expect it to return the object that contains country name and code after which I will update my state using

setPhoneNumberPrefix(objectReturned.code)

I don't understand what am I doing wrong. I feel like its something related to the function I am using?


Solution

  • If I understand correctly, props.data.country would be like Afghanistan and the return value of the function should be { label: "Afghanistan", value: "Afghanistan", code: "+93" }. You could use a function like that:

    function findCountry(label) {
            // I use a for loop because it allows me to get out of it easily by returning the value
            // forEach would also be fine but you would need to do it differently
            for (let continent of groupedCountries) {
                const res = continent.options.find(continent => continent.label.toLowerCase() === label.toLowerCase())
                if(res) return res;
            }
            // You should probably add a default value
            return 'default';
        }
    
    findCountry(props.data.country);