[英]how to check a string contain in an array of object
Hi I want to check if a string is contained on an array of objects. 嗨,我想检查对象数组中是否包含字符串。 I've tried some methods like
indexOf
or data.filter
, but I can't find a better solution. 我尝试了一些方法,例如
indexOf
或data.filter
,但是找不到更好的解决方案。 My array looks like: 我的数组看起来像:
0 [ {
"date": "12/19/2014 12:00:00 AM",
"type": "red",
"name": "hert",
"to": "418",
"newitem": [
{
"new": "gt",
"level": "typeone",}]
}]
I want to know if the string "typeone" is inside the 0[] array. 我想知道字符串“ typeone”是否在0 []数组内。
I've tried try : 我尝试过尝试:
var result = $.grep(data[0].newitem, function(e){ return e.level =="typeone"; });
but I didn't get the answer. 但我没有得到答案。
您是否在寻找Array.some
( MDN )
var result = data[0].newItem.some(function(obj) { return obj.level === 'typeone'})
这将返回true / false
var result = $.grep(data[0].newitem, function(e){ return e.level =="typeone"; }).length>0;
If you are trying to get the nested string from that object you are looking at doing this. 如果您试图从该对象获取嵌套字符串,那么您正在考虑这样做。
data[0].newitem[0].level
this will equal "typeone" 这将等于“打字机”
Your question is unclear. 您的问题不清楚。 Another tip is to check the type of data with
另一个提示是使用以下命令检查数据类型
//returns boolean
typeof Object === 'undefined'
typeof Object === 'Array'
typeof Object === 'String'
Try this: 尝试这个:
data[0].newitem.filter((e) => {return e.level == 'typeone'}).length
if length > 1
//string is present if length > 1
//字符串存在
Try this: 尝试这个:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.