如何循环和保存JSON数组中的值

这个问题在这里已经有了答案:

  • 在JavaScript中循环访问数组35个答案

  • 你可以简单地使用Array#map

    data.users.map(e =>
      (e.name.first ? e.name.first : '') + //Handles the first name
      (e.name.first ? ' ' : '') +          //Space between the names
      (e.name.last ? e.name.last : '')     //Handles the last name
    );
    

    演示:

    const data = {
      "users": [
        {
          "test": "123",
          "name": {
            "first": "bob",
            "last": "roppo"
          },
          "email": "bob@gmail.com",
          "phone": "+123456789"
        },
        {
          "test": "124",
          "name": {
            "first": "peter",
            "last": "sticer"
          },
          "email": "peter@gmail.com",
          "phone": "+123456789"
        }
      ]
    };
    
    let result = data.users.map(e => (e.name.first ? e.name.first : '') + (e.name.first ? ' ' : '') + (e.name.last ? e.name.last : ''));
    console.log(result);

    你可以使用map

    data.users.map( s => ( s.name.first || "" ) + " " + ( s.name.last || "" ) );
    

    如果两个属性值总是在那里,那么不需要短路

    data.users.map( s => s.name.first + " " +s.name.last );
    

    演示

    var data = {
      "users": [
        {
          "test": "123",
          "name": {
            "first": "bob",
            "last": "roppo"
          },
          "email": "bob@gmail.com",
          "phone": "+123456789"
        },
        {
          "test": "124",
          "name": {
            "first": "peter",
            "last": "sticer"
          },
          "email": "peter@gmail.com",
          "phone": "+123456789"
        }
      ]
    };
    
    var output =   data.users.map( s => s.name.first + " " + s.name.last );
    
    console.log(output);

    你可以使用forEach()

    var json = {
      "users": [
        {
          "test": "123",
          "name": {
            "first": "bob",
            "last": "roppo"
          },
          "email": "bob@gmail.com",
          "phone": "+123456789"
        },
        {
          "test": "124",
          "name": {
            "first": "peter",
            "last": "sticer"
          },
          "email": "peter@gmail.com",
          "phone": "+123456789"
        }
      ]
    }
    
    var res = [];
    json.users.forEach(function(p){
      var name = p.name.first + ' ' + p.name.last;
      res.push(name);
    });
    console.log(res);
    链接地址: http://www.djcxy.com/p/24539.html

    上一篇: how to loop and save values in array from JSON

    下一篇: read through json number array using javascript loop