我对 javascript/Angular 很陌生,正在考虑是否有一种简单的方法来获取 javascript 对象/数组中的第一项。
编辑:此时我确实可以控制如何格式化数组,所以也许有更好的方法使用 ID 作为键来做到这一点?
假设我想匹配数组中的第一项。我的想法是简单地循环遍历对象检查 ID 值。
js 函数可能如下所示:
app.controller('gamesController',function(){
//Function to load the games
this.loadGameIntoModal = function(game_id){
for (i=0;i<=length(games);i++){
if (games[i]['id'] === game_id)
{
this.games = games[i]['id'];
//Load the modal
$("#game_modal").modal();
break;
}
}
}
});
所以我的问题很简单,有没有比使用循环更好的方法?
var games = [
{
id : 1,
name : 'ABC Games',
games : [
{
id : 1,
name : 'ABC 1',
},
{
id : 2,
name : 'ABC 2',
} ,
{
id : 3,
name : 'ABC 3',
}
]
},
{
id : 2,
name : 'XYZ',
games : [
{
id : 4,
name : 'XYZ 1',
},
{
id : 4,
name : 'XYZ 2',
} ,
{
id : 5,
name : 'XYZ 3',
}
]
}
];
最佳答案
选择对象的第一项的键:
const items = { bill: 1231231, james: 545, scott: 8329, sarah: 999 };
const firstItem = Object.keys(items)[0]
console.log(firstItem)
选择对象的第一项的值:
const items = { bill: 1231231, james: 545, scott: 8329, sarah: 999 };
const firstItem = Object.values(items)[0]
console.log(firstItem)
听起来提问者想要FIND一个项目,但在这种情况下您只需使用.find
方法:
const items = { bill: 1231231, james: 545, scott: 8329, sarah: 999 };
const keyContaining545= Object.keys(items).find(key => items[key] === 545)
console.log(keyContaining545)
...或者他可能要求数组中的第一项,即 games[0]
。 [0]
是 games
数组中的位置。
关于javascript - 如何使用javascript选择javascript对象中的第一项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28614035/