Make an Array from JSON object values with jQuery

arrays, javascript, jquery, json

Solution

I think you should try like this:

$.getJSON( "ajax/test.json", function( data ) {
    console.log('loaded');
    var departement = []; // create array here
    $.each(data.personnes, function (index, personne) {
        departement.push(personne.departement); //push values here
    });
    console.log(departement); // see the output here
});

Problem

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 ?

Original source