0

If I have this type of object returned in javascript (as a result of $get)

[
  {
    "id": "1",
    "username": "john"
  },
  {
    "id": "2",
    "username": "bill"
  }
]

How would I search for the username "john" and if it exists return his ID

Thanks

i.e.

$.get( baseURL + "users/")
  .done(function( data ) {

    var usernames = data.results;

});
Ross M
  • 19
  • 6

1 Answers1

1

Use find():

var array =[
  {
    "id": "1",
    "username": "john"
  },
  {
    "id": "2",
    "username": "bill"
  }
];

var id = array.find(k=>k.username=='john')?.id;

console.log(id);
gorak
  • 5,233
  • 1
  • 7
  • 19