javascript - 如何在 json 数组中实现搜索

标签 javascript angularjs json

<分区>

我有一个像这样的 json 数组

[
  {"Id":1,
  "Name":"John"
  }, 
  {"Id":2,
  "Name":"Mathew"
  },
   {"Id":3,
  "Name":"Wilfred"
  },
   {"Id":4,
  "Name":"Gary"
  }
]

我需要使用这些数据实现自动完成功能。 因此,如果我搜索 "Wil",我应该得到 Wilfred 作为结果。我怎样才能进行类似于 JSON 数组中的 SQL LIKE

的搜索

最佳答案

使用Array.prototype.filter

var persons = [{
  "Id": 1,
  "Name": "John"
}, {
  "Id": 2,
  "Name": "Mathew"
}, {
  "Id": 3,
  "Name": "Wilfred"
}, {
  "Id": 4,
  "Name": "Gary"
}]
var searchTerm = "Wil";
var results = persons.filter(function(person) {
  return person.Name.indexOf(searchTerm) > -1;
});
console.log(results);

关于javascript - 如何在 json 数组中实现搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38454579/

相关文章:

javascript - 在不使用 () 包装的情况下调用 native Javascript 类型的方法

javascript - 当选中同一个 GridView 中的 CheckBox 时,如何启用和禁用 GridView 中的 LinkBut​​ton?

javascript - 未找到状态时 UI-Router Extras 和 future 状态的 404 页面

javascript - AngularJS Controller promise then 不是一个函数

javascript - (ES6) 使用输入字段过滤数据 (min.array)

java - Spring ajax 调用上的 400 错误请求

javascript - React 替代 ES6 类

php - 让javascript在外部链接点击时运行?

javascript - Angular next 和 prev 导航数学逻辑

java - 云端点不尊重 Jackson 注释