如何通过属性查找数组中的对象?

时间:2015-01-09 15:56:41

标签: javascript jquery

我从php脚本返回了以下数组。

$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"
    }
];

如何按id选择对象?等同于$obj = select * where id=$id的SQL,如果有意义的话。

5 个答案:

答案 0 :(得分:5)

您可以使用接受id作为参数的泛型函数并返回该对象(如果该id存在)

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

但如果您的输出正是您发布的内容并且您没有错过序列中的id,则可以将函数体缩小为

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

(在这种情况下,我假设你传递一个整数作为id

答案 1 :(得分:3)

您可以使用这样的小脚本:

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

答案 2 :(得分:1)

如果你正在使用jQuery,那就有一个很好的功能:$.grep

它根据过滤功能过滤输入数组。

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

答案 3 :(得分:0)

尝试

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

console.log(filtered("1"));

答案 4 :(得分:-2)

你会使用:

$data[0].id

所以,要通过它获取对象的id:

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

或者,只要你使用jQuery,这样的东西应该会有所帮助:

$.each(data, function(index) {  console.log(data[i].id); });