我有一个看起来像这样的对象:
var cities = {
"LA": [
{id:1, description:"This is a test"},
{id:3, description:"This is a third test"},
],
"Chicago": [
{id:2, description:"This is another test"}
],
"Vegas": [
{id:4, description:"This is another test"},
{id:5, description:"This is a fifth test"},
{id:6, description:"This is the last test"},
]
}
给定一个id我想找到相应的描述。
例如,如果给我id 1
,我想返回this is a test
。如果我得到 id 5
,它将返回 This is a fifth test
有谁知道如何做到这一点,使用 vanilla js,或者使用 lodash 或下划线?
最佳答案
var item = [].concat(...Object.values(cities)).find(o => o.id == 2)
item && item.description
// => "This is another test"
如果您要查找多个不同的描述,正如我在评论中所述,我会准备一个查找:
lookup = {}
Object.values(cities).forEach(a => a.forEach(e => lookup[e.id] = e))
lookup[2].description
// => "This is another test"
lookup[3].description
// => "This is a third test"
(请注意,此答案使用 ES6 语法,但如果您需要旧版浏览器支持,可以轻松转换为 ES5。)
关于javascript - 在具有id的对象中获取对应的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38969481/