0

I'm trying to get values from external json file and save some values in array. My code :

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

So I can get data from json but I'm not sure how I can add first and last name to array [bob rooppo, peter sticker]. Any help would be appreciated and my 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"
    }
  ]
}
fernando
  • 814
  • 1
  • 9
  • 24

3 Answers3

2

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);
Zenoo
  • 12,670
  • 4
  • 45
  • 69
0

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);
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
0

You can use 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);
Mamun
  • 66,969
  • 9
  • 47
  • 59