英文:
How to customize options in react-select?
问题
I'm using react-select but I have data in an object, not in an array, and the options only accept 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"
}
英文:
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"
}
答案1
得分: 1
你可以使用 Object.entries
将其转换为数组
const obj = {
'One': 'One',
'Two': 'Two',
};
const ccUsers = Object.entries(obj).map(([key, value]) => ({
label: key,
value
}))
console.log('>>>>>> ccUsers : ', ccUsers);
英文:
You can use Object.entries
to convert into Array
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const obj = {
'One': 'One',
'Two': 'Two',
};
const ccUsers = Object.entries(obj).map(([key, value]) => ({
label: key,
value
}))
console.log('>>>>> ccUsers : ', ccUsers);
<!-- end snippet -->
答案2
得分: 0
它接受一个类似于许多其他选择组件(例如antd Select)的{value: string, label:string}
数组。您需要在将其作为属性发送之前将数据进行转换。由于您已经有一个对象中的键值对,您可以使用Object.entries()
来实现这一点。链接:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论