Return key and value pair using a map

Asked

Viewed 199 times

1

Hello, I am trying to return a key and value pair using the function map(), however I am passing the information to my component via props, my component receives a text and a value inside it and returns an Option containing these values.

As you can see in the code each option has one value and a text. I created a variable data which is an object with the values but when I do the map it displays the whole array (yes it is wrong) however I do not know a way to make a variable returns the key pair and value, because my idea is to pass an array of objects, or an array (I do not know what would be the right way) and use the map to traverse by returning the value and the optionValue for Option.

Note: Each optionValue needs to have an option so that later these values can be captured in some way.

I had tried to make a map() inside another map() but it didn’t work.

I would like to know a way to do this in the right way, I thank you in advance ^^

const data = [
{
  optionValue: ['Teste1', 'Teste2', 'Teste3'],
},
{
  value: ['value1', 'value2', 'value3'],
},

];

 <Date option={data} />

Another file!

function Date({ option }) {
  return (
     <Select>
      {option.map((opt) => (
        <Option value={opt.optionValue}>{opt.value}</Option>
      ))}
    </Select>
   )    
 }

img

  • 1

    Can’t the date variable be an array with objects already with the desired structure? Type: const data = [{chave:'Teste1', value:'value1'},{chave:'Teste2',value:'value2'}].

  • this way it would not happen a conflict between the objects precisely because they have the same name?

1 answer

2


The object date is very bad for this type of task. If you have the option to edit it for an array of pairs { option, value}, everything will be better. If you don’t have this option, for example, if date is obtained via API, so you need to transform this object into something better. To transform

const data = [
  {
    optionValue: ["Teste1", "Teste2", "Teste3"]
  },
  {
    value: ["value1", "value2", "value3"]
  }
];

in

const data2 = [
  {
    option: "Teste1",
    value: "value1"
  },
  {
    option: "Teste2",
    value: "value2"
  },
  {
    option: "Teste3",
    value: "value3"
  }
];

just do

  const options = data[0].optionValue;
  const values = data[1].value;
  const pairs = options.map((option, index) => ({
    option,
    value: values[index]
  }));

This transformation only works if the arrays optionValue and value are the same size and are in the correct order. Then, inside the Date component, just make a map in this pair array:

<Select>
  {option.map(opt => (
    <Option value={opt.value}>{opt.option}</option>
  ))}
</Select>

I made an example at Codesandbox.

  • 1

    thanks so much for the help, it was clear and easy to understand ^^

Browser other questions tagged

You are not signed in. Login or sign up in order to post.