Javascript equivalent to PHP list()

Asked

Viewed 111 times

1

Is there any Javascript function equivalent to list() of PHP?

Suppose this JSON:

{  
   "ALERTA":[  
      {  
         "TITULO":"Erro!",
         "MENSAGEM":"Seu nome parece estar incorreto"
      },
      {  
         "TITULO":"Erro!",
         "MENSAGEM":"Seu nome parece estar incorreto"
      }
   ]
}

In PHP there is the possibility to use the list next to the foreach, to convert an index from an array to a variable.

foreach($json['ALERTA'] as list($titulo, $mensagem)){    
   // $titulo será "Erro!"
   // $mensagem será "Seu nome parece estar incorreto"
}

This makes it not necessary to use the indexes $variavel['TITULO'] and $variavel[MENSAGEM], in its place I use only $titulo and $mensagem.

In Javascript/Jquery I only know (and use) this method:

$.each(json['ALERTA'], function (nome, data) {
   // data['TITULO'] será "Erro!"
   // data['MENSAGEM'] será "Seu nome parece estar incorreto"
});

But I wanted to ELIMINATE the use of indexes ['TITULO'] and ['MENSAGEM'], only by aesthetic issues.

I wish for a result close to this:

$.each(json['ALERTA'], function (nome, list(titulo, mensagem)) {
   // titulo ser "Erro!"
   // mensagem ser "Seu nome parece estar incorreto"
});

So, as in PHP, I would not use the index. Is there any equivalent function list() PHP in Javascript, what would it be? If not, there is another solution to eliminate the use of indexes in this case (without being a new loop)?

1 answer

4


There is a way to do this using modern Javascript (ES6). I talked about this technique Destructuring assignment here, in this answer. You can also read more about it on MDN:Destructuring assignment.

If you combine this technique with the (also new) for of you can assign the values of these properties on the fly thus:

for (let { TITULO, MENSAGEM } of json.ALERTA) {
    console.log(TITULO, MENSAGEM);
}

Example: http://www.es6fiddle.net/irizeyxz/

If you need support for old browsers you can convert this with Babel. Create the code you need in ES6 and then convert. In this case the example code would look like this:

"use strict";

var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;

try {
    for (var _iterator = json.ALERTA[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
        var _step$value = _step.value;
        var TITULO = _step$value.TITULO;
        var MENSAGEM = _step$value.MENSAGEM;

        console.log(TITULO, MENSAGEM);
    }
} catch (err) {
    _didIteratorError = true;
    _iteratorError = err;
} finally {
    try {
        if (!_iteratorNormalCompletion && _iterator.return) {
            _iterator.return();
        }
    } finally {
        if (_didIteratorError) {
            throw _iteratorError;
        }
    }
}

To do it with old-fashioned code you can do it like this:

Array.prototype.lista = function() {
    var args = [].slice.call(arguments);
    var cb = args.pop();
    this.forEach(function(el) {
        var params = args.map(function(prop) {
            return el[prop];
        });
        cb.apply(this, params);
    });
}

and then to use:

json.ALERTA.lista('TITULO', 'MENSAGEM', function(tit, msg) {
    console.log(tit, msg);
});

jsFiddle: https://jsfiddle.net/x7hxmzpd/

Browser other questions tagged

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