【问题标题】:How to access property of suggestions coming from my AutoSuggest ( custom made using .filter() )如何访问来自我的 AutoSuggest 的建议的属性(使用 .filter() 自定义)
【发布时间】:2020-09-27 16:10:43
【问题描述】:

我正在使用 this.state 中的建议变量显示建议

suggestions = this.state.products
            .map((item) => item.name)
            .sort()
            .filter((v) => regex.test(v));

我的this.state.products 看起来像这样:

products = [
  {
    name: "Item1",
    category: "stock",
    id: 123
  },
  {
    name: "Item1",
    category: "product",
    id: 456
  },
  {
    name: "Item2",
    category" "item"
  }
]

this.state.suggestions 只是看起来像这样(假设用户输入是 Item1 或接近那个):

suggestions = ["Item1", "Item1"]

我怎样才能让它看起来像:

suggestions = [
  {
    name: "Item1",
    category: "stock"
  },
  {
    name: "Item1",
    category: "product"
  }
]

【问题讨论】:

    标签: javascript arrays reactjs sorting javascript-objects


    【解决方案1】:

    您可以在 mapping 时解构该对象,并仅将 name 属性传递给 filter。 像这样的:

    suggestions = this.state.products
                .map(({name, category}) => ({name, category}))
                .sort()
                .filter(({name}) => regex.test(name));
    

    【讨论】:

    • 先生,您是英雄!
    • 还有一件事,你能帮我找到包含给定id的对象的索引吗?我有array = [ { ... id: 489 }, { ... id: 978 } ] 并希望返回包含id 的对象的索引,该索引等于我的变量currentId。知道该怎么做吗?
    猜你喜欢
    • 1970-01-01
    • 2018-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多