【问题标题】:Validate if object has string验证对象是否有字符串
【发布时间】:2021-02-11 16:38:11
【问题描述】:

我有这个数组

switched = {"Restaurant":1,"Hotel":2,"Beauty shop":3,"Physiotherapist":4,"Dentist":5,"Bar":6,"Coffee shop":7}

还有这个对象

result = [{"Google Place URL":"http://www.restaurant.com","Business Type":"Restaurant"},{"Google Place URL":"http://www.hotel.com","Business Type":"Hotel"}]

我想验证result 的每个项目是否包含switched 的单词

另外,我已经在使用 for 单独返回每个项目

item[csvBusinessType] = Restaurant

如何验证item[csvBusinessType] 是否包含在switched 中?

我试过了

let n = switched.includes(item[csvBusinessType]);

但我得到Uncaught TypeError: switched.includes is not a function

【问题讨论】:

  • 如何验证 item[csvBusinessType] 是否包含在 switch 中?
  • switched 是一个对象。 .includesArray的方法
  • 嗯,我猜他们只是想看看switch 中的每个键是否与对应的result 索引匹配
  • @TheBombSquad 也许吧,但我们不是来猜测的。现在有了编辑,这个问题就更有意义了

标签: javascript string substring


【解决方案1】:

没有很好的本地方法。最好使用 lodash 库https://www.npmjs.com/package/lodash

这是一个例子

const _ = require('lodash');
console.log( _.includes(switched, item[csvBusinessType]));

【讨论】:

    【解决方案2】:

    我将对象转换为字符串并使用了包含,我不知道这是否是最好的方式,但我认为它是浏览器最支持的方式

          let businessListArray = JSON.stringify(switched);
          let checkBusiness = businessListArray.includes(item[csvBusinessType]);
    

    【讨论】:

      【解决方案3】:

      我想验证结果的每一项是否都包含switching的单词

      如果您想验证结果对象数组的每个项是否包含切换数组的单词,您应该查看 JS Array 方法并使用 Objects,就像@Andreas 建议的那样。 p>

      在这种特定情况下,您的 switched 对象的键似乎与您的 item 对象的 csvBusinessType 匹配。这很有帮助,因为我们可以使用 Object.keys() 来获取 switched 对象的所有键作为字符串数组。

      const businessTypes = Object.keys(switched) // = ["Restaurant","Hotel","Beauty shop","Physiotherapist","Dentist","Bar","Coffee shop"]
      

      现在我们已经获取了您要检查的键,我们可以使用 JS Array method every()result 对象数组中的每个对象执行测试。在这种情况下,我们将测试对象的Business Type 是否包含在我们新创建的businessTypes 数组中。

      const resultsValid = result.every((resultObject) => businessTypes.includes(resultObject["Business Type"]));
      

      resultsValid 是一个布尔值,如果 result 中的所有对象都具有与您的 switched 对象的键之一匹配的业务类型,则为 true。

      注意:您可能需要在进行其中一些比较之前检查 Letter Casing,除非您只想明确匹配完全匹配(例如,“Beauty shop”将不匹配“Beauty Shop”)。

      【讨论】:

        猜你喜欢
        • 2015-08-06
        • 1970-01-01
        • 1970-01-01
        • 2020-03-01
        • 2019-11-15
        • 2018-08-23
        • 2022-12-11
        • 2021-02-13
        • 1970-01-01
        相关资源
        最近更新 更多