Henrique
Henrique

Reputation: 133

How to get object key and value without knowing directly object key?

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>

Upvotes: 0

Views: 975

Answers (2)

Og&#252;n Birinci
Og&#252;n Birinci

Reputation: 728

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.

Upvotes: 3

<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()

Upvotes: 1

Related Questions