简体   繁体   中英

Get a Object property from array of objects when I have the value of another property in the same object

In JavaScript if I have this value in a variable...

var selectedId = '2';

And I have this array of objects below....

var itemsArray = [
    {
        id: 1,
        name: 'Item 1',
    },
    {
        id: 2,
        name: 'Item 2',
    },
    {
        id: 3,
        name: 'Item 3',
    },
    {
        id: 4,
        name: 'Item 4',
    },
]; 

How can I get the itemsArray name value from the object that the value selectedId has.

In this example I would have the value of 2 in selectedId and need to get the itemsArray[n][name] of Item 2

You can use .filter like this

 var selectedId = 2; var itemsArray = [ { id: 1, name: 'Item 1', }, { id: 2, name: 'Item 2', }, { id: 3, name: 'Item 3', }, { id: 4, name: 'Item 4', }, ]; var result = itemsArray.filter(function (el) { return el.id === selectedId; }); var name = result[0] && result[0].name; console.log(name); 

This might be what you need:

// Give me everything in itemsArray where:
itemsArray.filter(function(item){

    // its id is the one I'm looking for,
    return (item.id === selectedId) 

// and give them to me in this form:
}).map(function(element){ 

    // just the name
    return element.name 
})

map() and filter(), along with reduce() and forEach(), can be extremely interesting and useful. Especially if you're using this problem to better understand arrays or programming, I'd suggest learning how to use them all.

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