【问题标题】:How do I dynamically list a nested object?如何动态列出嵌套对象?
【发布时间】:2023-02-25 22:58:21
【问题描述】:

除了为每个嵌套对象(或电影标题)列出的演员是最后一部电影 Fantastic Mr. Fox 之外,我有工作代码。我无法弄清楚我的代码有什么问题。

let movieData = {
    "The Darjeeling Limited": {
      plot: "A year after their father's funeral, three brothers travel across India by train in an attempt to bond with each other.",
      cast: ["Jason Schwartzman", "Owen Wilson", "Adrien Brody"],
      runtime: 151,
      rating: 7.2,
      year: 2007,
    },
    "The Royal Tenenbaums": {
      plot: "The eccentric members of a dysfunctional family reluctantly gather under the same roof for various reasons",
      rating: 7.6,
      year: 2001,
      cast: ["Gene Hackman", "Gwnyeth Paltrow", "Anjelica Huston"],
      runtime: 170,
    },
    "Fantastic Mr. Fox": {
      year: 2009,
      plot: "An urbane fox cannot resist returning to his farm raiding ways and then must help his community survive the farmers' retaliation.",
      cast: [
        "George Clooney",
        "Meryl Streep",
        "Bill Murray",
        "Jason Schwartzman",
      ],
      runtime: 147,
      rating: 7.9,
    },
    "The Grand Budapest Hotel": {
      rating: 8.1,
      runtime: 159,
      year: 2014,
      plot: "A writer encounters the owner of an aging high-class hotel, who tells him of his early years serving as a lobby boy in the hotel's glorious years under an exceptional concierge.",
      cast: ["Ralph Fiennes", "F. Murray Abraham", "Mathieu Amalric"],
    },
  };
  //Practising data retrieval
  console.log(movieData);
  console.log(movieData["Fantastic Mr. Fox"]);
  console.log(movieData["Fantastic Mr. Fox"].year);
  console.log(movieData["Fantastic Mr. Fox"]['year']);
  console.log(movieData["Fantastic Mr. Fox"].cast[1]);
  
  // let object = document.getElementById("test").innerHTML;
  // console.log(object);
  // let object2 = document.getElementById("test");
  // console.log(object2);
  
  //Practising data render
  // let foxYear = movieData["Fantastic Mr. Fox"]['year'];
  
  // document.getElementById("test").innerHTML = foxYear;
  
  //Practising object conversion
  let a = Object.keys(movieData);
  let b = Object.values(movieData);
  let c = Object.entries(movieData);
  console.log(a);
  console.log(b);
  console.log(c);
  
  //Rendering movie names to html page
  const movieListNames = Object.keys(movieData);
  console.log(movieListNames);
  //Passing in an array of movie names as a parameter
  function addSpaceToName(array) {
    for (let movie = 1; movie < array.length; movie++) {
      array[movie] = " " + array[movie]; 
    }
    return array;
  }
  addSpaceToName(movieListNames);
  document.getElementById("movie-list").innerHTML = movieListNames;
  
  function dropDown(movieName) {
    moviesDropDown.addEventListener('change', movieNameKey => {
      movieDetails.innerHTML = movieName;
      console.log(movieName)
    })}
  
  const movieDetails = document.getElementById('movie-details');
  
  // experimenting with an array
  movieDataArray = Object.entries(movieData);
  for (let i in movieDataArray) {
    console.log(movieDataArray[i]);
  };
  //drop down list
  //get element by id
  const moviesDropDown = document.getElementById('movies-drop-down');
  // for...in loop (for enumerable object)
  for (let movieName in movieData) {
    //create option element
    let movieOptionElement = document.createElement("option");
    //set the value of the "*value* attribute" (of the option element) to movieName key (of object)
    movieOptionElement.setAttribute('value', movieData[movieName]);
    //text to be display in drop down list is movieName key
    let movieOptionText = document.createTextNode(movieName);
    //add to option element
    movieOptionElement.appendChild(movieOptionText);
    //add to select element
    moviesDropDown.appendChild(movieOptionElement);
  
    dropDown(movieData[movieName]["cast"])
  };
  
  //display details when selected from drop down list
  /* moviesDropDown.addEventListener('change', movieNameKey => {
    movieDetails.innerHTML = movieNameKey.target.value;
    console.log(movieNameKey.target);
  }); */
  
  const newMovie = document.getElementById('new-movie');

【问题讨论】:

标签: javascript html


【解决方案1】:

您似乎希望在用户从下拉列表中选择电影时显示电影的演员表。

这些是它的问题:

  • 您为每部电影调用一次函数dropDown,然后每次都在&lt;select&gt; 元素上分配一个事件处理程序。那是不对的:你应该只听一次给用户选择,而不是 4 次。所以 dropDown 应该只被调用一次——在循环之外。

  • dropDown 无法将要选择的电影作为参数,因为你不知道现在用户可能会选择什么未来.所以这个函数不应该有任何参数。

  • change 事件处理程序应该检查用户取了哪个值,所以它应该查看moviesDropDown.value。但是,要使其正常工作,您需要解决下一个问题:

  • &lt;option&gt; 元素的 value 属性设置不正确。您的代码当前将该属性值设置为目的,到movieData[movieName],但那将被字符串化为[object Object],这是无用的信息。相反,您应该将该属性值设置为:movieName

没问题,但是 addSpaceToName 函数太过分了。您可以使用本机数组方法 join 实现此目的。

通过这些更正,它应该可以工作:

let movieData = {
    "The Darjeeling Limited": {
      plot: "A year after their father's funeral, three brothers travel across India by train in an attempt to bond with each other.",
      cast: ["Jason Schwartzman", "Owen Wilson", "Adrien Brody"],
      runtime: 151,
      rating: 7.2,
      year: 2007,
    },
    "The Royal Tenenbaums": {
      plot: "The eccentric members of a dysfunctional family reluctantly gather under the same roof for various reasons",
      rating: 7.6,
      year: 2001,
      cast: ["Gene Hackman", "Gwnyeth Paltrow", "Anjelica Huston"],
      runtime: 170,
    },
    "Fantastic Mr. Fox": {
      year: 2009,
      plot: "An urbane fox cannot resist returning to his farm raiding ways and then must help his community survive the farmers' retaliation.",
      cast: [
        "George Clooney",
        "Meryl Streep",
        "Bill Murray",
        "Jason Schwartzman",
      ],
      runtime: 147,
      rating: 7.9,
    },
    "The Grand Budapest Hotel": {
      rating: 8.1,
      runtime: 159,
      year: 2014,
      plot: "A writer encounters the owner of an aging high-class hotel, who tells him of his early years serving as a lobby boy in the hotel's glorious years under an exceptional concierge.",
      cast: ["Ralph Fiennes", "F. Murray Abraham", "Mathieu Amalric"],
    },
  };

  // Make use of .join method to display list nicely  
  document.getElementById("movie-list").innerHTML = Object.keys(movieData).join(", ");
  
  function dropDown() { // No parameter
    moviesDropDown.addEventListener('change', () => {
      // Look up selected value, and use it to retrieve the corresponding movie data 
      movieDetails.innerHTML = movieData[moviesDropDown.value].cast.join(", ");
    })
  }
  
  const movieDetails = document.getElementById('movie-details');
  
  const moviesDropDown = document.getElementById('movies-drop-down');
  for (let movieName in movieData) {
    let movieOptionElement = document.createElement("option");
    movieOptionElement.setAttribute('value', movieName); // Should not be object
    let movieOptionText = document.createTextNode(movieName);
    movieOptionElement.appendChild(movieOptionText);
    moviesDropDown.appendChild(movieOptionElement);
  };
  dropDown(); // Only one call -- no argument
Movie list: <span id="movie-list"></span><br>
Select a movie: <select id="movies-drop-down"></select><br>
movie-details: <span id="movie-details"></span>

【讨论】:

    猜你喜欢
    • 2011-10-25
    • 2017-04-20
    • 1970-01-01
    • 2021-11-15
    • 1970-01-01
    • 2017-04-28
    • 1970-01-01
    • 1970-01-01
    • 2011-07-25
    相关资源
    最近更新 更多