在具有id的对象中获取对应的值
Get corresponding value in an object with an id
我有一个看起来像这样的对象:
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
,我会想要 return this is a test
。如果给我 id 5
它会 return This is a fifth test
有谁知道如何做到这一点,使用 vanilla js,或者使用 lodash 或下划线?
这里使用的是JQuery
for (var city in cities) {
if (cities.hasOwnProperty(city)) {
$.each(cities[city] , function(i, item) {
if(item.id == 1) {
console.log(item.description);
}
});
}
}
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。)
循环对象for in
和循环数组forEach
function findById(d){
var result;
for(var k in cities){
cities[k].forEach(function(v){
if(v.id == d) result = v.description;
});
}
return result;
}
console.log(findById(5));
我有一个看起来像这样的对象:
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
,我会想要 return this is a test
。如果给我 id 5
它会 return This is a fifth test
有谁知道如何做到这一点,使用 vanilla js,或者使用 lodash 或下划线?
这里使用的是JQuery
for (var city in cities) {
if (cities.hasOwnProperty(city)) {
$.each(cities[city] , function(i, item) {
if(item.id == 1) {
console.log(item.description);
}
});
}
}
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。)
循环对象for in
和循环数组forEach
function findById(d){
var result;
for(var k in cities){
cities[k].forEach(function(v){
if(v.id == d) result = v.description;
});
}
return result;
}
console.log(findById(5));