0

I have the following array returned from a php script.

$data =  [
    {
        "id": "1",
        "created_at": "2015-01-02 15:17:29",
        "updated_at": "2015-01-02 15:17:29",
        "name": "Minecraft",
        "description": "",
        "location": "ideaLab",
        "cost": "20.00",
        "min_age": "7",
        "max_age": null,
        "start_date": "2014-11-06",
        "end_date": "2014-12-11",
        "start_time": "16:30:00",
        "end_time": "17:30:00",
        "registration_start_date": "2014-10-28",
        "registration_end_date": "0000-00-00",
        "program_id": "1",
        "max_attendees": "12"
    },
    {
        "id": "2",
        "created_at": "2015-01-02 15:17:29",
        "updated_at": "2015-01-02 15:17:29",
        "name": "Mini Makers",
        "description": "",
        "location": "ideaLab",
        "cost": "18.00",
        "min_age": "9",
        "max_age": "7",
        "start_date": "2014-11-04",
        "end_date": "2014-12-09",
        "start_time": "16:30:00",
        "end_time": "17:30:00",
        "registration_start_date": "2014-10-28",
        "registration_end_date": "0000-00-00",
        "program_id": "2",
        "max_attendees": "20"
    }
];

How do I select the object by id? something like the SQL equivalent of $obj = select * where id=$id if that makes sense.

atmd
  • 7,430
  • 2
  • 33
  • 64
Phil
  • 2,176
  • 10
  • 33
  • 56

5 Answers5

5

You could use a generic function that accepts the id as argument and return the object (if the id exists)

function getObjectById(id) {
   for (var i = 0; i < $data.length; i++) {
      if ($data[i]['id'] === id) {
         return $data[i];
      }
   }
   return {};
}

but if your output it's exactly what you posted and you have not missing id in the sequence you could just reduce the body of the function to

return (id > 0 && id <= $data.length) ? $data[id - 1] : {}

(in this scenario I assume you pass an integer number as id)

Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177
  • 1
    The most straight forward answer, but I would probably return `null` if not found – Rhumborl Jan 09 '15 at 16:01
  • 1
    I would do == instead of === because id is a string and may be used as a number ? – Hacketo Jan 09 '15 at 16:02
  • 1
    @Hacketo I just prefer by default strict comparison. as long as the values are all strings and you pass a string as parameter then `===` is fine – Fabrizio Calderan Jan 09 '15 at 16:05
  • Is this PHP or JavaScript? – Praveen Kumar Purushothaman Jan 09 '15 at 16:07
  • it's vanillaJS @PraveenKumar – Fabrizio Calderan Jan 09 '15 at 16:09
  • @FabrizioCalderan Your use of `$` in front of the variable name was the confusion. Thanks for the clarification. – Praveen Kumar Purushothaman Jan 09 '15 at 16:10
  • Thanks my output is as posted. I was not aware that it was missing a id in the sequence. I will see if there is a way to add that to the php output. I used Laravel framework .toJson() function. I would have to ensure that the id of the object will always align to the id inside the object though which I would rather not do. – Phil Jan 09 '15 at 17:19
  • @Hacketo thanks == is better for me, it is stored as a number in my database but from my research some databases might output as string so I think it best to be as type agnostic as possible here. – Phil Jan 09 '15 at 18:25
3

You can use a small script like this:

function findJSONById(needle, jsonString)
{
  var finalJSON = {};
  $.each(JSON.parseJSON(jsonString), function (key, value) {
    if (value["id"] == needle)
    {
      finalJSON = value;
      return false; // break the loop
    }
  });
  return finalJSON;
}
Rhumborl
  • 16,349
  • 4
  • 39
  • 45
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
1

If you are using jQuery there is a nice function: $.grep

It filters input array based on filter function.

var objectWithId2 = $.grep(data, function (obj) { 
    return obj.id == 2; 
})[0];
Rev
  • 57
  • 4
0

Try

var filtered = function(data, id) {
  return data.filter(function(items, i) {
    return items.id === id
  })
};

console.log(filtered("1"));
guest271314
  • 1
  • 15
  • 104
  • 177
-2

You would use :

$data[0].id

So, to get the object by it's id:

$data[$id+1]  //so long as their position in the array is not shuffled.

Or, so long as you are using jQuery, something like this should be helpful:

$.each(data, function(index) {  console.log(data[i].id); }); 
rm-vanda
  • 3,122
  • 3
  • 23
  • 34