我试图将此数组中每个对象的Genre属性“链接”到输出到value内部用户的title属性。

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


尝试使用IndexOf方法至少通过搜索“流派”来检索元素,但是它输出-1

最佳答案

您可以使用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'));

关于javascript - 使用其他属性在数组内查找对象的属性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40384324/

10-12 12:50