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

时间:2018-05-02 13:20:05

标签: javascript arrays json ajax

我试图从外部json文件获取值并在数组中保存一些值。我的代码:

$.getJSON("https://link.to.my.json", function(data) {
    console.log(data); // this will show the info it in  console
});

所以我可以从json获取数据,但我不知道如何在数组[bob rooppo,peter sticker]中添加名字和姓氏。任何帮助,将不胜感激 和我的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"
    }
  ]
}

3 个答案:

答案 0 :(得分:2)

您只需使用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);

答案 1 :(得分:0)

您可以使用map

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

如果两个属性值始终存在,则不需要短路

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

<强>演示

&#13;
&#13;
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);
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您可以使用forEach()

&#13;
&#13;
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);
&#13;
&#13;
&#13;