【问题标题】:How to augment search function to include array within objects如何增强搜索功能以在对象中包含数组
【发布时间】:2018-07-12 03:48:38
【问题描述】:

给定这种格式的数据:

// projects.json
{
    businessName: "",
    address: "",
    city: "",
    reference: "",
    contacts: [
        {
            name: ""
            phone: ""
        },
        {
            name: ""
            phone: ""
        }
    ],
}

...和一个搜索功能(顺便说一句,这是一个 Vue 应用程序),它迭代 json 的“项目”对象:

export default {
    computed: {
        filteredProjects: function() {
            const searchTerm = this.search.toLowerCase();
            if (!searchTerm) {
                return false;
            }
            return this.projects.filter((project) => {
                return (project.businessName.toLowerCase().match(searchTerm)) ||
                         (project.reference.toLowerCase().match(searchTerm));
            });
        }
    } // computed
} // export default

...如何扩充此功能以在搜索中包含每个“项目”对象中的“联系人”数组,例如:

return this.projects.filter((project) => {
    return (project.businessName.toLowerCase().match(searchTerm)) ||
             (project.reference.toLowerCase().match(searchTerm)) ||
             // PSEUDO-CODE (searching contact name doesn't throw error but returns 100% of the data):
             (project.contacts.filter((el) => {
                 el.name.toLowerCase().match(searchTerm);
             }))
});

提前感谢您的任何帮助或建议,

威士忌酒。

【问题讨论】:

  • (projects.contacts.filter(.....).length > 0)
  • @RoyJ 感谢您的回复。由于您的建议显示过滤器 arg 周围的封闭括号,我假设您的意思是:'(project.contacts.filter((el) =>{ el.name.toLowerCase().match(searchTerm); }).length > 0) ; ...但这并没有返回预期的任何结果。我误解了什么?谢谢
  • 你需要在el.name前面加上return
  • @RoyJ 谢谢;关于“返回”的又一个“duh”时刻......但是你介意解释为什么在联系人过滤器中需要长度方法而不是在外部对象的过滤器中吗?
  • 因为filter返回一个数组,即使是空的也是一个真值。其他表达式使用match

标签: arrays object search filter vue.js


【解决方案1】:

两件事:

  1. filter 返回一个数组,所以它的值永远为真;您需要检查它的 length 以在它为空时获取错误值
  2. 您需要在 project.contacts.filter 箭头函数中添加一个 return

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-22
    • 1970-01-01
    • 1970-01-01
    • 2016-05-26
    • 2014-09-24
    • 1970-01-01
    相关资源
    最近更新 更多