简体   繁体   中英

Select2 Optgroup Result Set

I was hoping to receive help with the following problem.

I get back the following JSON data:

{
    "0": {
    "Name": "Hello World OPTGROUP",
    "values": [
        {
            "Vector": "[REDACTED]",
            "Name": "Hello World",
            "Value": "[REDACTED]",
            "Matched": null
        }
    ]
},    
{
    "1": {
    "Name": "Lorem Ipsum OPTGROUP",
    "values": [
        {
            "Vector": "[REDACTED]",
            "Name": "Lorem Ipsum",
            "Value": "[REDACTED]",
            "Matched": null
        }
    ]
}

How do I go about build a processResults dropdown result set that includes labels for each array?

<select>
    <optgroup label="Hello World OPTGROUP">
    <option>Values[0] Value</option>
    <option>Values[1] Value</option>
    <optgroup label="Lorem Ipsum OPTGROUP">
    <option>Values[0] Value</option>
    <option>Values[1] Value</option>
</select>

Your JSON data wasn't quite ...complete so I put in some {} where I thought you needed them.

One way to do this would be:

 const data = [{ "0": { "Name": "Hello World OPTGROUP", "values": [ { "Vector": "[REDACTED]", "Name": "Hello World", "Value": "[REDACTED]", "Matched": null } ] } }, { "1": { "Name": "Lorem Ipsum OPTGROUP", "values": [ { "Vector": "[REDACTED]", "Name": "Lorem Ipsum", "Value": "[REDACTED]", "Matched": null }, { "Vector": "[REDACTED]", "Name": "Lorem Ipsum", "Value": "[REDACTED]2", "Matched": null } ] } }]; const optMap = e => `<option>${e.Value}</option>` let templateInner = data .map(e=>e[Object.keys(e)]) .map(e=>` <optgroup label="${e.Name}"> ${e.values.map(optMap).join('')}`) .join('') let template = `<select>${templateInner} </select>` console.log(template) 

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