检查foreach循环包含一个值

问题描述:

我有以下的JSON检查foreach循环包含一个值

success{ "fname": [ "The fname field is required." ], "lname": [ "The lname field is required." ], "email": [ "The email field is required." ], "password": [ "The password field is required." ], "password_confirmation": [ "The password confirmation field is required." ] }

什么,我做的是,如果值包含为必填字段,然后CONSOLE.LOG它。我保存在VAR数据的JSON

angular.forEach(data, function(value, key) 
       { 
        if(value ==("field is required")){ 
         console.log (key) 
        } 
       }) 

我试过。载,.match,没有什么工作

+0

请检查您的JSON数据,我注意到的值实际上是一个数组。 – yukuan

也得到了包括方法。

在这里,DOC对包括:http://www.w3schools.com/jsref/jsref_includes.asp

而且为的IndexOf商务部: http://www.w3schools.com/jsref/jsref_indexof.asp

我亲自找到的IndexOf解决方案有点脏,因为它不是为这个做,但它似乎是最常见的解决方案

你也可以研究在问,这里之前在*的是你的问题的答案:

How to check whether a string contains a substring in JavaScript?

尝试:

   if(value.indexOf("field is required") > -1){ 
        console.log (key) 
       } 

这将检查如果字符串 “字段是必须的” 。

+0

我得到这个错误:ionic.bundle.js:25642类型错误:无法读取属性“的indexOf”空 – noor

如果你的JSON瓦莱斯是[“的---现场需要”]你是测试字符串与“字段是必需的”相等,那么你的if条件将永远不会评估为真。

你需要让你的价值的子部分,如果这是要评估的条件是什么。您可以使用字符串拆分,搜索,substr或其他字符串方法来获取该部分值:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String

您需要使用带有.match()或.search()的正则表达式。你也可以使用

var idx = value.indexOf('field'); 
var str = value.slice(idx); 
if(str == "field is required")... 

angular.forEach(data, function(value, key){ 
    if(value.indexOf("field is required") > -1){ 
    console.log(key); 
    } 
}); 
+0

的我得到这个错误:ionic.bundle.js:25642类型错误:无法读取属性空的“的indexOf” – noor