skip to Main Content

I am having the list of all the objects in the array

let array = [
  { name: "Galaxy S22", storage: "128GB" },
  { name: "Galaxy S22 5G", storage: "128GB" },
  { name: "Galaxy S22 Ultra", storage: "256GB" },
  { name: "Galaxy S22", storage: "256GB" }
 ];

I have an another object which holds the object with name and its storages

  const storages = {
    Galaxy S22: ["128GB", "256GB"],
    Galaxy S22 5G: ["128GB"],
    Galaxy S22 Ultra: ["256GB"]
   }

I am trying to display in the UI respective storages for the respective brand name. But i am able to see all the storages for all the brands

All the storages in all the brands

function generateAndDisplayRadioButtons(list, storages) {
   return (
    <div>
        {
            list.map((item) => {
                return (
                    <div key={item.name}>
                        {storages[item.name]?.map((storage)=>{
                           return (
                                <div key={storage} className='flexCss'>
                                <input className="radioCss" type="radio" name={item.name} value={storage} />
                                <strong>{storage}</strong>
                            </div>
                            )
                        })

                        }
                    </div>
                )
            })
        }

    </div>
)
};

In the render i am trying to display with

<div>{generateAndDisplayRadioButtons(array, storages)}</div>

2

Answers


  1. You have a mismatch in the structure.
    I think you should change your function to this:

    function generateAndDisplayRadioButtons(list, storages) {
    return (
        <div>
            {list.map((item) => (
                <div key={item.name}>
                    {storages[item.name]?.map((storage) => (
                        <div key={storage} className='flexCss'>
                            <input className="radioCss" type="radio" name={item.name} value={storage} />
                            <strong>{storage}</strong>
                        </div>
                    ))}
                </div>
            ))}
        </div>
    );
    

    }

    Login or Signup to reply.
  2. You should include the keys of storages object within double quotes.

      const storages = {
        "Galaxy S22": ["128GB", "256GB"],
        "Galaxy S22 5G": ["128GB"],
        "Galaxy S22 Ultra": ["256GB"],
      };
    

    With that included I have run the code in my machine. It works fine with the following output on the browser:
    enter image description here

    You have Glaxy S22 two times in the list array which is printing the same content twice.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search