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 ?
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;
};
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With