【问题标题】:Filtering through an array based on its ID [closed]根据 ID 过滤数组 [关闭]
【发布时间】:2020-08-03 12:58:16
【问题描述】:

我需要遍历我的过滤数组。指定数组中的对象具有描述、时间、id 等多个属性。 我想根据 ID 过滤数组,所以我想取回具有所需 ID 的对象,这样我就可以使用它并打印出它的描述、时间等。

这是我的 v-for:

 <h1
          class="content"
          v-for="(record, index) of filteredRecords"
          :key="index"
          :class="{ 'is-active': index === activeSpan }"
        >
          
          <strong>{{ record.description }}</strong>
        </h1>

这就是我过滤数组的方式:

filteredRecords() {
  return this.records.filter(record => {
    return record.id === this.id;
  });
}

如何从这个函数返回整个对象?

我现在拥有的:

records:[{
  description: "xy",
  time: 12,
  id: 5
}, {
  description: "xy",
  time: 12,
  id: 6

}, {
  description: "xy",
  time:12321,
  id:7
}]

我想要得到的是例如所有 id 为 7 的东西:

想要的输出:

filteredRecords:[{
  description: "xy",
  time: 12321,
  id: 7
}]

【问题讨论】:

  • “我需要过滤器中的整个数组”——.filter() 的重点是过滤 out 原始数组的一些元素。如果您不想这样做,那么使用.filter() 是没有意义的。
  • 如果您需要整个数组,则不是过滤,它们是相反的概念。请更好地解释“过滤器”应该做什么
  • 我知道了,我应该怎么做,比如映射?
  • 你想达到什么目的?请提供之前的数据示例和之后需要的数据
  • 你所做的已经是你想要的。您当前的代码有什么问题?

标签: javascript vue.js filter vue-router


【解决方案1】:

我认为答案很简单,就是您在“v-for”中缺少 ()。所以,不要这样:

v-for="(record, index) of filteredRecords"

你应该有这个:

v-for="(record, index) of filteredRecords()"

【讨论】:

  • 我认为它是一个计算属性,在这种情况下 () 是可选的,但你可能是对的
  • 它只是不工作..我不知道为什么,我应该在哪里添加我的过滤记录方法?在方法中还是在计算中?但我认为这不是问题
  • 我错了,你的答案是正确的。
【解决方案2】:

问题不在过滤,而在vue部分:

代替

v-for="(record, index) of filteredRecords"

使用

v-for="(record, index) in filteredRecords"

【讨论】:

  • 它们不相同,一个使用for..in语法,另一个使用for..of语法
  • 不,不幸的是它不起作用。
  • @endoftheworld 什么不起作用?在里面添加debugger; 并打开开发工具。在filteredRecords 中,将过滤器返回的数组分配给一个变量,并通过记录它来检查它的值。检查this.id 的值。返回一个虚拟数组并检查它是否显示在 HTML 中。检查 HTML 并检查呈现的代码。请。调试。您的。代码。
猜你喜欢
  • 2022-01-12
  • 1970-01-01
  • 2019-04-29
  • 1970-01-01
  • 1970-01-01
  • 2020-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多