A variable comes to my page through localStorage with a value like "Website development".

And I have an array

db[0][{'page_title':'Разработка сайтов','id':'92'}] db[1][{'page_title':'Мобильные приложения','id':'94'}] db[2][{'page_title':'Дизайн','id':'96'}] db[3][{'page_title':'ИТ-инфраструктура','id':'98'}] 

I need to find the value "Website Development" in this array, and return the key. Please tell me how to do this?

And by the way, it would be nice to return false if not found.

And yet, you can solve the problem, if I knew how to add something to the array using push:

 db['Разработка сайтов'][{'page_title':'Разработка сайтов','id':'92'}] db['Мобильные приложения'][{'page_title':'Мобильные приложения','id':'94'}] db['Дизайн'][{'page_title':'Дизайн','id':'96'}] db['ИТ-инфраструктура'][{'page_title':'ИТ-инфраструктура','id':'98'}] 


  • what will happen if I tell you that you should not use arrays, but regular hashes: {'Website Development': {'page_title': 'Website Development', 'id': '92'}, 'Mobile Applications': { 'page_title': 'Mobile applications', 'id': '94'}, 'Design': {'page_title': 'Design', 'id': '96'}, 'IT infrastructure': {'page_title' : 'IT infrastructure', 'id': '98'}} then access will be extremely simple: obj ['Website development']; // will return the object {'page_title': 'Website development', 'id': '92 '} yes, and hasOwnProperty('Акваланг') will return false , just as you need it - Specter

1 answer 1

For example, you can do this

 function find(arr, value) { for (i in arr) for (j in arr[i]) if (arr[i][j]== value) return [i, j]; return false; }; arr=[{'x':5, 'y':6, 'z':7}, {'b':8, 'c':9}]; alert(find(arr, 9)); 

Returns an array of keys

 [1, 'c'] 

If by key you mean 'id', then you can get it

 arr[find(arr, 'строка поиска')[0]]['id'] 
  • debagger writes: Bad for in variable 'i' Bad for in variable 'j' And the script does not work. - chuikoff
  • Strange. I checked before posting to mobile opera. - ReinRaus