LPG
LPG

Reputation: 842

Select2 id cannot be an Object?

With select2, there are 2 required parameters for each list item: "id", and "text". All is well if both your id and text are String types. However when I try to make id into an Object, I get errors. Inspecting in the console, I can see that id = ["[object Object]"]

The code I'm using to generate the list for select2:

var list = [ "apple", "banana", "orange"]
var list =  _.map(list, function(each){
 return { id: { myName: each, otherData: 1 }, text: each }
});

$(".js-example-basic-single").select2({
  data: list
});

I can't see anywhere in the docs whether "id" can only be a string and not an object.

Is it possible to have "id" be an object? If so, is there any special syntax?

Upvotes: 3

Views: 521

Answers (3)

LPG
LPG

Reputation: 842

I got confirmation from the maintainers of Select2, that it needs to be a string on the latest version. https://github.com/select2/select2/issues/4227

Since id and text must be strings, the only way to add variables is to have the object be:

{ id: 'string', text: 'string', userDefinedKey: 'string' }

Upvotes: 0

Hitmands
Hitmands

Reputation: 14199

Ids are usually strings, sometimes numbers, because these types are easy to compare. Personally I'dont know select2, but, I think that it uses ids as dom references, so, ids must be strings.

try something like that:

var list = ['banana', 'apple', 'orange']
   .map((fruit, index) => {type: fruit, id: (Number(index || 0) + 1).toString()})
   //.sort() //sort fruits as you want, etc...
;

Upvotes: 1

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85573

I don't know jquery-select2 but just looking at the example code, you need to do like this:

return [{id: 0, myName: each, otherData: 1}, {id: 1, text: each}];

Upvotes: 1

Related Questions