[英]How do I update selected values in react multiselect
I have a modal in which I edit my model. In my form, I also have a multi-select tag field.我有一个模式,我可以在其中编辑我的 model。在我的表单中,我还有一个多选标签字段。 The "tags" is an array of objects with labels and values as show below.
“标签”是一组具有标签和值的对象,如下所示。
There is a dummy tags object (mimicking a database) which all the tags are selected from.有一个虚拟标签 object(模仿数据库),所有标签都是从中选择的。
const dummyTags = [
{ label: "Test 1", value: "Test 1" },
{ label: "Test 2", value: "Test 2" },
{ label: "Test 3", value: "Test 3" },
];
So, if I selected "Test 1" and "Test 2", my tags array becomes (only the values are then saved in the database):因此,如果我选择“测试 1”和“测试 2”,我的标签数组将变为(只有值会保存在数据库中):
const tgs = [
{
label: "Test 1",
value: "Test 1"
},
{
label: "Test 2",
value: "Test 2"
}
];
However, during update, the tags come from the database as ['Test 1','Test 2']
.但是,在更新期间,标签来自数据库
['Test 1','Test 2']
。
I want to use the tags from the database shown in the line above to compare the dummyTags
array so I can have a new array of objects with values like the tgs
array above.我想使用上面一行中显示的数据库中的标签来比较
dummyTags
数组,这样我就可以拥有一个新的对象数组,其值类似于上面的tgs
数组。
At the moment, this is what I am doing:目前,这就是我正在做的:
let newtags = [];
if (groupTags.length > 0) { //groupTags is the tags from the database
groupTags?.forEach((tag) => {
newtags.push({ label: tag, value: tag });
});
}
This works, but I think it's not reliable.这行得通,但我认为它不可靠。 What if the label and value are not the same for a particular tag?
如果特定标签的 label 和值不同怎么办?
Is there a better way of implementing this?有没有更好的方法来实现这个?
const arr = ['Test 1','Test 2', 'Test 3'] const result = arr.map(d => ({label: d, value: d})); console.log(result)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.