【问题标题】:Add an array to another array without index vuejs将一个数组添加到另一个没有索引vuejs的数组
【发布时间】:2020-05-05 07:45:00
【问题描述】:

我会在 Vuejs 中创建一个调查应用程序。

我有这个功能可以将检查的答案发布到我的数据库中:

postAnswerTest: function(modelId, topicId, questionId, answerId) {
      var finalAnswer = [];
      finalAnswer[questionId] = [modelId, topicId, questionId, answerId];
      this.finalArray.push(finalAnswer);
      console.log(this.finalArray);
    },

我想要的是在不创建新索引的情况下将 finalAnswer 数组插入到 finalArray 数组中,因为索引必须是 questionId。

所以我知道push方法不好,但是不知道怎么做。

有什么想法吗?

非常感谢。

【问题讨论】:

  • 是否可以选择使用键为 questionId 并保存适当数组而不是 array of arrays 的对象?
  • 如果你需要一个数组项有一个特定的 id,你可能想要使用一个对象而不是一个数组...

标签: javascript arrays vue.js


【解决方案1】:

这将是我评论的代码,不知道使用一个对象是否适合你......

postAnswerTest: function(modelId, topicId, questionId, answerId) {
    var finalAnswer = {modelId, topicId, questionId, answerId};
    this.finalObject[questionId] = finalAnswer;
    console.log(this.finalObject);
  },

【讨论】:

  • 是的,这可能是一个很好的解决方案,我将看看是否可以将这个对象数组用于我的应用程序的下一个功能。谢谢!
  • 如果您在取回 questionIds 时遇到问题:您可以通过const questionIds = Object.keys(this.finalObject);获取 questionIds 数组
  • 我设法通过您的第一个解决方案获得了我想要的东西,非常完美!再次感谢
猜你喜欢
  • 2021-12-08
  • 2021-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-22
  • 2021-12-10
  • 2016-08-16
相关资源
最近更新 更多