如何在对象数组(结构)中查找字符串

时间:2013-06-13 05:11:46

标签: javascript jquery arrays

这是一个小例子:

var distinctValues = [];
distinctValues.push("Value1");
distinctValues.push("Value2");

var firstValue = distinctValues[0];

var searchResults = [];

var data = grid.jqGrid('getGridParam', 'data');
data.forEach(function (row) {

  searchResults[searchResults.length] =
  {
    "ID"       : row.ID,
    "CreatedBy": row.CreatedBy,
    "UpdatedBy": row.UpdatedBy
  }
}

如何在searchResults数组中查看firstValue(“Value1”)并检索CreatedBy信息?

//something like this - this is wrong syntax by the way
if ($.inArray(firstValue, searchResults) != -1) {
      alert(searchResults["CreatedBy"]);
}

1 个答案:

答案 0 :(得分:1)

我想你可能想这样做:

var searchResults = [];
data.forEach(function (row) {

  searchResults.push({ //Push to push the record to the array
    "ID"       : row.ID,
    "CreatedBy": row.CreatedBy,
    "UpdatedBy": row.UpdatedBy
  });
}

您可以使用jquery $ .inArray或Array.prototype.indexOf

searchResults是一个对象数组,因此请使用索引器searchResults[index]["CreatedBy"]而不是searchResults["CreatedBy"]

var idx = searchResults.indexOf(firstValue); //or var idx = $.inArray(firstValue, searchResults)
if (idx  > -1) {
      alert(searchResults[idx]["CreatedBy"]);  //item Found
}

$.inArray的语法没有错,前提是您的代码中包含了jquery。

由于您的匹配是针对对象属性的,因此您可以尝试:

   var result = $.grep(searchResults, function(value)
   {
       return value.ID === firstValue;
   });

  console.log(result[0].CreatedBy); //result will be an array of matches.