Live search localstorage (search in array)

匿名 (未验证) 提交于 2019-12-03 01:03:01

问题:

this is what I what I have:

And now I want to make the live search. The point is when you type in the textbox you automatically have to search in the localstorage with something that equals the text in the search box. All the data that doesn't matches dissapears.

$("#searchbox").keyup(function(){      // Retrieve the input field text     var searchtext = $(this).val();      // Loop through the local storage     var a = {};     a = JSON.parse(localStorage.getItem('session'));      alert(a); }); 

As you can see I make an alert and my output is this:

{"21114":{"id":"21114","external_id":"","sessiongroupid":"1844","eventid":"5588","order":"0","name":"localStorage  HTML5 Session","description":"localstorage","starttime":"2013-04-23  12:00:00","endtime":"2013-04-23  13:30:00","speaker":"","location":"","mapid":"0","xpos":"0.000000","ypos":"0.000000","maptype":"plan","imageurl":"","presentation":"","organizer":"0","twitter":"","allowAddToFavorites":"0","allowAddToAgenda":"0","votes":"0","url":"","venueid":"0"},"21115":{"id":"21115","external_id":"","sessiongroupid":"1845","eventid":"5588","order":"0","name":"tweede","description":"tweede","starttime":"2013-04-03  00:00:00","endtime":"2013-04-04  00:00:00","speaker":"","location":"","mapid":"0","xpos":"0.000000","ypos":"0.000000","maptype":"plan","imageurl":"","presentation":"","organizer":"0","twitter":"","allowAddToFavorites":"0","allowAddToAgenda":"0","votes":"0","url":"","venueid":"0"}} 

Now I want to search on the name. Can somebody help me how to do this?

回答1:

Simply iterate over the object

var json = JSON.parse(localStorage);  for(obj in json) {     console.log(json[obj].name); //compare this with your "searchtext" } 

Prints

localStorage HTML5 Session tweede 

You can simply check inside the loop if .name matches whatever you want and process it.



回答2:

try this simple code

dataArray.filter(function(object) {    return object.name == new RegExp('text to search', 'gi') }) 

change .name with your key want to search



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!