Hello!

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'}] 

thank

  • 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