Materialize with Array as DataSource

5

I'm using the autocomplete function of materialize , how do I use a local JSON and fill select from this? In the official documentation, there is only one using an object.

data: {
    "Apple": "null",
    "Microsoft": "null",
    "Google": "http://placehold.it/250x250"
}

... and what I want to use is something like this ...

data: [{
    "field": "null",
    "field2": "a",
    "field3": "b",
    "field4": "c"
},
{
    "field": "null",
    "field2": "a",
    "field3": "b",
    "field4": "c"
},
{
    "field": "null",
    "field2": "a",
    "field3": "b",
    "field4": "c"
}]

... but it does not work, I already try formatting the information at value , label , as well as at jQueryUI , but it does not work either ...

var prog = $.map(this._programasService.getProgramas(), function (i)
{
    return {
        label: i.field2,
        value: i.field3
    };
});
    
asked by Alexandrei Delgadillo 22.10.2016 в 17:47
source

3 answers

1

In the end I ended up building an object with what I needed since each value in my case is unique

ngOnInit()
{
    this.programas = this._programasService.getProgramas();

    var program = $.map(this._programasService.getProgramas(), function (i)
    {
        return {
            id: i.prgprg_descripcion,
            text: i.prgprg_nombre
        };
    });

    var arr = {};
    for (var i = 0; i < program.length; i++)
    {
        arr[program[i].id] = program[i].text;
    }


    $(this.el2.nativeElement).autocomplete({
        data: arr
    });
}
    
answered by 24.10.2016 в 20:21
0

Have you tried putting an array into a field in the first JSON array?

For example:

data: [{
    "field1": "null",
    "field2": "a",
    "field3": "b",
    "newData": [{
                "field": "null",
                "field2": "a",
                "field3": "b",
                "field4": "c"
               }]
}]

Keep in mind that in newData you could insert all the arrays you need clear.

Then you could access it like this:

label: i.newData.field2 ;

I hope I helped you. Greetings

    
answered by 24.10.2016 в 19:22
0

As you have already mentioned, the data parameter of the jQuery autocomplete plugin of materialize needs a key-value object.

Regarding the transformation of the model you work with, you can use reduce to avoid traversing the array twice and generating a more compact code.

ngOnInit(){
    this.programas = this._programasService.getProgramas();

    var data = this.programas.reduce(function (accumulator, currentValue){
        accumulator[currentValue.pgrpgr_descripcion] = currentValue.pgrpgr_nombre;
        return accumulator;
    }, {});

    $(this.el2.nativeElement).autocomplete({
        data: data
    });
}

Note: Both map as it reduces are widely supported, for what you could use instead of the jQuery function.

    
answered by 25.11.2016 в 11:19