NeoVe
NeoVe

Reputation: 3907

For loop on javascript object

I have this javascript object:

var input = [
    {
        id: 1,
        title: 'michael',
        favorite: 'bmw'
    },
    {
        id: 2,
        title: 'steve',
        favorite: 'bentley'
    },
    {
        id: 3,
        title: 'denise',
        favorite: 'ford'
    },
]

And this is my function, it is supposed to loop through input and when called with console.log print a specific favorite, depending on which element on the list has been read by the loop.

findYourFavorite = function() {
    for(let x=0; x<3; x++) {
        if(input[x].title) {
            var response = input[x].favorite
        }
    }
    return response
}

If I run console.log(findYourFavorite('michael')) it will always print the same title, which is the last one in the javascript object (denise).

Ex:

console.log(findYourFavorite('michael'))
ford

It is not working randomly, as it should, I hope I'm explaining myself, if You need further clarification please do let me know.

Upvotes: 0

Views: 53

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371233

Your condition if(input[x].title) { makes no sense - all the titles are truthy. Only assign to response if the title is equal to the parameter (which you also need to define).

var input = [
    {
        id: 1,
        title: 'michael',
        favorite: 'bmw'
    },
    {
        id: 2,
        title: 'steve',
        favorite: 'bentley'
    },
    {
        id: 3,
        title: 'denise',
        favorite: 'ford'
    },
];

const findYourFavorite = function(titleToFind) {
    for(let x=0; x<3; x++) {
        if(input[x].title === titleToFind) {
            var response = input[x].favorite
            return response;
        }
    }
}
console.log(findYourFavorite('denise'))

Or, much more concisely, use .find:

var input = [
    {
        id: 1,
        title: 'michael',
        favorite: 'bmw'
    },
    {
        id: 2,
        title: 'steve',
        favorite: 'bentley'
    },
    {
        id: 3,
        title: 'denise',
        favorite: 'ford'
    },
];

const findYourFavorite = (titleToFind) => input
  .find(({ title }) => title === titleToFind)
  .favorite;
console.log(findYourFavorite('denise'))

Upvotes: 3

Related Questions