Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make an Array from JSON object values with jQuery

I have this simple JSON file (test.json):

{"personnes":[
            {
                "name":"Super",
                "firstname":"Mario",
                "adresse":["45 rue du poirier","6700","Strasbourg"],
                "departement": "bas-rhin",
            },
            {
                "name":"Super",
                "firstname":"Luigi",
                "adresse":["10 rue du muguet","6700","Strasbourg"],
                "departement": "eure",
            }
]}

For some reasons, I need to get each "departement" values to be stored in a single array like this :["bas-rhin","eure"]

I learned that $.makeArray() can do the job, but didn't find out how. Here is my jQuery :

$( document ).ready(function() {
    $.getJSON( "ajax/test.json", function( data ) {
        console.log('loaded');
        var departement;
        var departements = $.each(data.personnes, function (index, personne) {
            departement = personne.departement;
            var arr = $.makeArray(departement);
            console.log(arr)
        });
    });
});

With that code, I get 2 seperate arrays : ["eure"] and ["bas-rhin"].

Here is the question : How can I solve it and get these values in a single array ?

like image 459
notjb Avatar asked Dec 06 '22 03:12

notjb


1 Answers

Use map. It's much simpler:

var arr = data.personnes.map(function (el) {
  return el.departement;
});

console.log(arr); // ["bas-rhin", "eure"]

Alternatively, using jQuery's $.map:

var arr = $.map(data.personnes, function (el) {
  return el.departement;
});

Fiddle

If you need a polyfill for map:

if (!('map' in Array.prototype)) {
  Array.prototype.map = function (mapper, that /*opt*/) {
    var other = new Array(this.length);
    for (var i = 0, n = this.length; i < n; i++) {
      if (i in this) { other[i] = mapper.call(that, this[i], i, this); }
    }
    return other;
  };
}
like image 182
Andy Avatar answered Dec 15 '22 16:12

Andy