通过值查找javascript中对象的索引 [英] Find index of object in javascript by a value
问题描述
我在json中有很长的时区列表,如下所示.
I have a long list of timezones in json like the following.
[
{"value": "Pacific/Niue", "name": "(GMT-11:00) Niue"},
{"value": "Pacific/Pago_Pago", "name": "(GMT-11:00) Pago Pago"},
{"value": "Pacific/Honolulu", "name": "(GMT-10:00) Hawaii Time"},
{"value": "Pacific/Rarotonga", "name": "(GMT-10:00) Rarotonga"},
{"value": "Pacific/Tahiti", "name": "(GMT-10:00) Tahiti"},
{"value": "Pacific/Marquesas", "name": "(GMT-09:30) Marquesas"},
{"value": "America/Anchorage", "name": "(GMT-09:00) Alaska Time"},
{"value": "Pacific/Gambier", "name": "(GMT-09:00) Gambier"},
{"value": "America/Los_Angeles", "name": "(GMT-08:00) Pacific Time"},
{"value": "America/Tijuana", "name": "(GMT-08:00) Pacific Time - Tijuana"},
{"value": "America/Vancouver", "name": "(GMT-08:00) Pacific Time - Vancouver"},
]
我设置了用户时区检测功能,该功能返回的时区字符串为"America/Los_Angeles"
I have user timezone detection set up which returns a timezone string as "America/Los_Angeles"
使用Java语言,我想找到json对象中America/Los_Angeles
的位置,因此我可以使用其名称"来预填充表单字段.
Using Javascript I want to find the where America/Los_Angeles
is in the json object so I can use its "name" to prefill a form field.
我对indexOf()
方法很熟悉,但是无法弄清楚在这种情况下如何使用它.有没有一种简单的方法可以解决这个问题,或者我应该只遍历整个列表?
I am familiar with indexOf()
method, but can't work out how to use it in this situation. Is there a simple way to handle this or should I just foreach through the whole list?
推荐答案
使用Java语言,我想找到America/Los_Angeles所在的位置 json对象,以便我可以使用其名称"来预填充表单字段.
Using Javascript I want to find the where America/Los_Angeles is in the json object so I can use its "name" to prefill a form field.
您可以使用findIndex
var index = arr.findIndex( s => s.value == "America/Los_Angeles" )
,现在使用此索引来预填充一个字段.
and now use this index to prefill a field.
或者简单地使用find
返回对象
Or simply use find
to return an object
var element = arr.find( s => s.value == "America/Los_Angeles" )
并在element
本身中设置名称字段
and set the name field in the element
itself
element.name = "somevalue";
这篇关于通过值查找javascript中对象的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!