简体   繁体   中英

How to select first item in javascript object using javascript?

I am quite new to javascript/angular and was pondering whether or not there is an easy way to grab the first item in a javascript object/array.

EDIT: I do have control at this point in time in how I format the array, so perhaps there is a better way to do this using ID as keys?

Lets say I want to match the first item in the array. My thinking is to simply loop through the object checking the ID value.

The js function may look something like this:

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;
            }
        }
    }
});

So my question is simply, is there a better way to do this than to use a loop?

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',
                }
            ]

        }
    ];

There are several different ways to do this, as other answers have valid suggestions. You mentioned that you're willing to restructure your object a bit. So this is an alternative that I've used:

var games = {
    1: {id   : 1,
        name : 'ABC Games',
        games : [
                {
                    id   : 1,
                    name : 'ABC 1',
                },
                {
                    id   : 2,
                    name : 'ABC 2',
                }
        ]
    },
    2: {id   : 2,
        name : 'XYZ',
        games : [
                {
                    id   : 1,
                    name : 'XYZ 1',
                },
                {
                    id   : 2,
                    name : 'XYZ 2',
                }
        ]
    },
}

With this structure, the ID is also the object's key. This has the advantage, that now you can just pass an ID, and reference it directly without loops. games['1'].name //ABC Games .

And just for convenience, we leave the id property within each object to make it easier for referencing later if needed.

Select the object's first item's key:

 const items = { bill: 1231231, james: 545, scott: 8329, sarah: 999 }; const firstItem = Object.keys(items)[0] console.log(firstItem)

Select the object's first item's value:

 const items = { bill: 1231231, james: 545, scott: 8329, sarah: 999 }; const firstItem = Object.values(items)[0] console.log(firstItem)

It sounds like the person asking the question wants to FIND an item though in which case you would just use the .find method:

 const items = { bill: 1231231, james: 545, scott: 8329, sarah: 999 }; const keyContaining545= Object.keys(items).find(key => items[key] === 545) console.log(keyContaining545)

... Or maybe he's asking for the first item in the array which is simply games[0] . The [0] is the position in the games array.

If you bring in a library like lodash ( https://lodash.com ) you can use their methods rather than handrolling it.

With lodash it'd be: var firstItem = _.first(games) ( https://lodash.com/docs#first )

If you're familiar with .net, lodash is basically linq for JS.

var firstProperty;
var firstValue;
for(firstProperty in target) { firstValue = target[firstProperty]; break; }

now firstProperty and firstValue should contain the first declared property key/value pair in the object or array ( key would be an int in this case ) of the object ( at least when I tested it with the {} syntax)

if you want to make sure it is the first property that belongs to that object can do this

for(firstProperty in target) if(target.hasOwnProperty(firstProperty)) { 
    firstValue = target[firstProperty]; 
    break; 
}

Like this solution because it is simple and doesn't require you to bring in another dependency if you don't need it

Two things:

  1. In JavaScript, there is no guaranteed "order" of properties in and Object . . . only in Arrays , so, by far, the simplest way to make your data sequentially structured, is to use an Array .
  2. If the only use of the id attributes is to indicate that order, you would be much better off using the indeces of an Array in to identify the different items, than a property within the object, since those indeces are more easily accessed. I'd suggest updating your structure to this:

     var games = [ { name : 'ABC Games', games : ['ABC 1', 'ABC 2', 'ABC 3'] }, { name : 'XYZ', games : ['XYZ 1', 'XYZ 2', 'XYZ 3'] } ]; 

With that structure, you can still use a loop to iterate through the array structure, but you can also, very easily, access specific elements, using the indeces. Some examples:

games[0].games[0] ---> "ABC 1"
games[1].games[0] ---> "XYZ 1"
games[1].games[2] ---> "XYZ 3"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM