TheNuttyStudent TheNuttyStudent - 1 month ago 10
Javascript Question

Find object's property inside array using other property

I'm trying to "link" the Genre property in each of these objects inside this array to the title property that outputs to the user inside

value
.

var movies= [{
"Title": "Platoon",
"Genre": "War"
}, {
"Title": "Pulp Fiction",
"Genre": "Crime"
}];

var name = value;
//console.log(name) outputs as title the user clicked on just fine

var genre = ...["Genre"]; //no idea how to go about this
//this should say genre = ["Genre"] in object where ["Title"] is same as value


Tried the IndexOf method to at least retrieve the element by searching for "Genre", but it outputs
-1
.

Answer

You could use Array#some.

function findGenre(title) {
    function search(a, i) {
        if (a.Title === title) {
            index = i;
            return true;
        }
    }
  
    var index;
    if (movies.some(search)) {
        return movies[index].Genre;
    }
}

var movies= [{ Title: "Platoon", Genre: "War" }, { Title: "Pulp Fiction", Genre: "Crime" }];

console.log(findGenre('Platoon'));