0

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.

3
  • 3
    Right.... because you are overlaying the value of response ever iteration. stackoverflow.com/questions/500431/… Commented Sep 30, 2020 at 22:08
  • 2
    How do you want this to behave? Commented Sep 30, 2020 at 22:10
  • 1
    Your findYourFavorite function does not take any parameters, which is already a flaw Commented Sep 30, 2020 at 22:10

1 Answer 1

3

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.