Home > Software design >  How to get object key and value without knowing directly object key?
How to get object key and value without knowing directly object key?

Time:06-21

I'm building a React component, that receives an array of objects, but I'm curious about this:

How can I get an object key and value inside map function, without knowing exactly the object key?

I have this interface:

export interface ISelectOption {
    [key: string]: string;
}

And the type of options variable is an array of ISelectOption.

I would like to do something like this, if it's possible:

<select {...rest}>
    {options.map((option, i) => {
       return (
           <option key={i} value={option.key}>
               {option.value}
           </option>
       );
   })}
</select>

CodePudding user response:

Object.keys(options.object).map((key, i) => (
              <option key={i} value={key}>
               {options.object[key]}
              </option>
            )

In this way, without knowing the keys, you can access all of then, looping and access the values.

CodePudding user response:

<select {...rest}>
    {options.map((option, i) => {
       const optionKey = Object.entries(option)[0][0]
       const optionValue = Object.entries(option)[0][1]
       return (
           <option key={i} value={optionKey}>
               {optionValue}
           </option>
       );
   })}
</select>

Method Object.entries() returns an array of [key, value] pairs, so if you are sure your option have only one property then you can use the above snippet, if not then you must iterate over the array returned by Object.entries()

  • Related