使用其他属性在数组中查找对象的属性

时间:2016-11-02 15:55:24

标签: javascript

我正在尝试将此数组中每个对象中的Genre属性“链接”到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 内输出给用户的title属性。

-1

尝试使用IndexOf方法至少通过搜索“Genre”来检索元素,但它输出*{ box-sizing:border-box; } .con{ /*position:relative;*/ float:left; width:70%; /*width:600px;*/ background:orange; padding:4px; } .side{ /*position:absolute; left:0; top:0;*/ padding:4px; float:left; width:30%; height:100vh; background:yellow; filter:opacity(.8); font-size:50px /* for only 30% width, I would consider decreasing the font size */ }

4 个答案:

答案 0 :(得分: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'));

答案 1 :(得分:0)

一个简单的for循环应该这样做。

var genre;
for(var i=0; i< movies.length; i++) {
  if (movies[i].Title === name) {
    genre = movies[i].Genre;
    break; // stop the loop assuming title is unique
  }
}

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

var name = 'Pulp Fiction';

var genre;
for(var i=0; i< movies.length; i++) {
  if (movies[i].Title === name) {
    genre = movies[i].Genre;
    break;
  }
}

alert(genre);
&#13;
&#13;
&#13;

答案 2 :(得分:0)

你可以,

  var found = movies.filter(function(m) { 
     return m.Title === value 
  });

  if (found.length > 0) { 
    console.log(found[0].Genre); // or handle some way different if more than one match found 
  }

答案 3 :(得分:0)

您可以使用for..of循环,对象解构通过检查点击元素的.innerHTML是否等于对象的Title属性的值来获取值

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

var divs = document.querySelectorAll("div");
var [value, genre] = [null, null];
for (let el of divs) {
  el.onclick = (e) => {
    for (let props of movies) {
      let {Title, Genre} = props;
      if (Title === e.target.innerHTML) {   
        [value, genre] = [Title, Genre];
        console.log(`value:${value}, genre:${genre}`);
        break;
      }
    }
  }
}
&#13;
<div>Platoon</div>
<div>Pulp Fiction</div>
&#13;
&#13;
&#13;