简体   繁体   中英

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. 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.

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

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'] .

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.

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM