【问题标题】:How to take an input from a form and store a variable in an existing object如何从表单中获取输入并将其作为顶层键存储在现有对象中?
【发布时间】:2022-11-04 20:56:35
【问题描述】:

我正在尝试从表单中获取数据并将其添加到现有的对象movieData。我能够传递所有较低的键值对,但作为顶层键的标题无法识别并作为字符串传递。任何想法我怎么能做到这一点?在此先感谢您的帮助。

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,
    }
...
}

function handleForm(event) {
  event.preventDefault();
  const newTitle = document.getElementById("newTitle").value;
  const newRating = document.getElementById("newRating").value;
  const newYear = document.getElementById("newYear").value;
  const newRuntime = document.getElementById("newRuntime").value;
  const newCast = document.getElementById("newCast").value;
  const newPlot = document.getElementById("newPlot").value;
  
  var addNewMovie = {
   newTitle : {
      rating: newRating,
      year: newYear,
      runtime: newRuntime,
      cast: newCast,
      plot: newPlot,
    }
  };
        Object.assign(movieData, addNewMovie)
console.log(movieData);
displayMovieData();
    }

form.addEventListener('submit',handleForm);

我已经尝试过了,但不幸的是 newTitle 没有注册并作为字符串传递。

【问题讨论】:

    标签: javascript-objects key-value


    【解决方案1】:
    var addNewMovie = {
       [newTitle] : {
          rating: newRating,
          year: newYear,
          runtime: newRuntime,
          cast: newCast,
          plot: newPlot,
        }
      };
    

    我意识到我需要在第一个键/变量周围添加方括号。 https://www.geeksforgeeks.org/how-to-use-a-variable-for-a-key-in-a-javascript-object-literal/

    【讨论】:

      猜你喜欢
      • 2018-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多