1

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

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.