您好我想检查对象数组中是否包含字符串。我尝试了一些方法,例如indexOf
或data.filter
,但我无法找到更好的解决方案。我的数组看起来像:
0 [ {
"date": "12/19/2014 12:00:00 AM",
"type": "red",
"name": "hert",
"to": "418",
"newitem": [
{
"new": "gt",
"level": "typeone",}]
}]
我想知道字符串" typeone"在0 []数组内。
我尝试过尝试:
var result = $.grep(data[0].newitem, function(e){ return e.level =="typeone"; });
但我没有得到答案。
答案 0 :(得分:1)
您是否正在寻找Array.some
(MDN)
var result = data[0].newItem.some(function(obj) { return obj.level === 'typeone'})
答案 1 :(得分:1)
这将返回true / false
var result = $.grep(data[0].newitem, function(e){ return e.level =="typeone"; }).length>0;
答案 2 :(得分:0)
如果您尝试从该对象获取嵌套字符串,那么您正在考虑这样做。
data[0].newitem[0].level
这将等于“typeone”
你的问题不清楚。另一个提示是使用
检查数据类型//returns boolean
typeof Object === 'undefined'
typeof Object === 'Array'
typeof Object === 'String'
答案 3 :(得分:0)
试试这个:
Running `bundle update` will rebuild your snapshot from scratch, using only
the gems in your Gemfile, which may resolve the conflict.
Bundler could not find compatible versions for gem "logstash":
In Gemfile:
logstash-filter-cipher (>= 0) java depends on
logstash (< 2.0.0, >= 1.4.0) java
Could not find gem 'logstash (< 2.0.0, >= 1.4.0) java', which is required by gem 'logstash-filter-cipher (>= 0) java', in any of the sources.
data[0].newitem.filter((e) => {return e.level == 'typeone'}).length
//字符串存在
答案 4 :(得分:0)
试试这个:
var arr = [{
"date": "12/19/2014 12:00:00 AM",
"type": "red",
"name": "hert",
"to": "418",
"newitem": [
{
"new": "gt",
"level": "typeone"
}]
}];
console.log(containsString(arr, "typeone")); // contains "typeone" --> true
function containsString(arr, strSearch) {
var same = false;
for (var p in arr) {
var entry = arr[p];
var type = toString.call(entry);
if (type.indexOf("Object") > -1 ? true : type.indexOf("Array") > -1 ? true : false) {
return containsString(entry, strSearch);
} else {
same = (entry === strSearch);
if (same) return same;
}
} // end for loop
return same;
}// end iterate