javascript - 如何使用javascript选择javascript对象中的第一项?

标签 javascript jquery angularjs

我对 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/

相关文章:

javascript - 为什么加载时有点击,但点击时却没有?

javascript - 当移动标记到达一定latlng时触发事件

jquery - 插入将复制的可选空格

jquery按类获取嵌套项的值

javascript - 在 Angular 组件中动态分配 templateUrl

javascript - 如何动态设置 md-autocomplete 的必填字段

javascript - 握手期间 ASP.NET Core WebSocket 失败

javascript - "Draggable"只垂直拖动?

javascript - ng-change 和 ng-click 可以与单个按钮一起使用吗?

javascript - 如何在用 php、apache 服务器编写的网站子程序上激活 vue-router 的历史记录模式?