how to loop and save values in array from JSON

This question already has an answer here:

  • Loop through an array in JavaScript 35 answers

  • You can simply use 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
    );
    

    Demo:

    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);

    You can use map

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

    If both property values will always be there, then no need of short-circuiting

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

    Demo

    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/24540.html

    上一篇: getElementsbyClassName可以查找并处理所有元素

    下一篇: 如何循环和保存JSON数组中的值