skip to Main Content

I’m using react-select but I have a data in object not in array & in options only accepting array values. How can I solve it?

 <Select
   options={ccUsers}
   onChange={handleChange}
 />

Working data :-

  const ccUsers = [
    { value: 'One', label: 'One' },
    { value: 'Two', label: 'Two' },
  ];

But getting data in this format :-

const ccUsers = {
    "test": "testing",
    "test": "testing"
}

2

Answers


  1. You can use Object.entries to convert into Array

    const obj = {
      'One': 'One',
      'Two': 'Two',
    };
    const ccUsers = Object.entries(obj).map(([key, value]) => ({
      label: key,
      value
    }))
    console.log('>>>>>  ccUsers : ', ccUsers);
    Login or Signup to reply.
  2. It accepts an array of {value: string, label:string} like many other Select components, such as antd Select. You need to transform your data before sending it as a prop inside Select. Since you have key-value pairs in an object already, you can use Object.entries() to do that. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries

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