Pass field for array sorting in VUE

Asked

Viewed 48 times

1

I am trying to pass the name of the field where I want the array to be ordered, when I put the name directly works, passing the name through the variable no, I commented the lines the way it is not functional.

computed: {
    list_cob_frequencia() {
        var campo_var = 'nome_campo';
        var ordem = this.ordem_campo_cobertura_frequencia[this.campo_ordenar_frequencia]
            .ordem;
        return this.json_cobertura_frequencia.slice().sort(function(a, b) {
            if (ordem == 'ASC') {
                return (a.nome_campo< b.nome_campo) ? 1 : -1
                //return (a.campo_var< b.campo_var) ? 1 : -1;                  
            } else {
                return (b.nome_campo< a.nome_campo) ? 1 : -1;
                //return (b.campo_var< a.campo_var) ? 1 : -1;
            }
        });
    }
},
  • 1

    Have you tried a['nome_do_campo']? or in your case a[campo_var]?

  • 1

    I had not tried this way, it worked. Thank you!

  • 1

    I put together an answer.

1 answer

1


Has 2 ways to access the property of an object that can be by point or by square brackets, in your case it must be by square brackets to make your code dynamic in access to certain property, example:

object.property
object["property"]

Solution:


computed: {
    list_cob_frequencia() {
        var campo_var = 'nome_campo';
        var ordem = this.ordem_campo_cobertura_frequencia[this.campo_ordenar_frequencia]
            .ordem;
        return this.json_cobertura_frequencia.slice().sort(function(a, b) {
            if (ordem == 'ASC') {
                return (a[campo_var] < b[campo_var]) ? 1 : -1                  
            } else {
                return (b[campo_var] < a[campo_var]) ? 1 : -1;
            }
        });
    }
},

Browser other questions tagged

You are not signed in. Login or sign up in order to post.