使用jQuery从JSON对象值创建一个Array

jus*_*ile 4 javascript arrays jquery json

我有这个简单的JSON文件(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",
            }
]}
Run Code Online (Sandbox Code Playgroud)

出于某些原因,我需要将每个"departement"值存储在一个单独的数组中,如下所示:["bas-rhin","eure"]

我了解到$.makeArray()可以做到这一点,但没有找到方法.这是我的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)
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

使用该代码,我得到2个单独的数组:["eure"]["bas-rhin"].

这是一个问题:我如何解决它并在单个数组中获取这些值?

And*_*ndy 9

使用map.它更简单:

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

console.log(arr); // ["bas-rhin", "eure"]
Run Code Online (Sandbox Code Playgroud)

或者,使用jQuery $.map:

var arr = $.map(data.personnes, function (el) {
  return el.departement;
});
Run Code Online (Sandbox Code Playgroud)

小提琴

如果您需要填充地图:

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;
  };
}
Run Code Online (Sandbox Code Playgroud)


Jai*_*Jai 5

我想你应该这样试试:

$.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
});
Run Code Online (Sandbox Code Playgroud)