2017-02-27 91 views
0

您好我想檢查一個字符串是否包含在一個對象數組中。我試過一些方法,如indexOfdata.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

您的問題沒有清晰準確!你想知道數組的類型或數組中的項目的類型? – Smit

回答

0

試試這個:

data[0].newitem.filter((e) => {return e.level == 'typeone'}).length 

if length > 1 // string是目前

1

你是正在尋找Array.someMDN

var result = data[0].newItem.some(function(obj) { return obj.level === 'typeone'}) 
0

如果你想從你正在尋找這樣該對象的嵌套字符串。

data[0].newitem[0].level 

這將等於 「typeone」

你的問題還不清楚。另一個技巧是檢查數據的類型與

//returns boolean 
typeof Object === 'undefined' 
typeof Object === 'Array' 
typeof Object === 'String' 
1

這將返回真/假

var result = $.grep(data[0].newitem, function(e){ return e.level =="typeone"; }).length>0; 
0

試試這個:

var arr = [{ 
 
\t "date": "12/19/2014 12:00:00 AM", 
 
\t "type": "red", 
 
\t "name": "hert", 
 
\t "to": "418", 
 
\t "newitem": [ 
 
\t { 
 
\t \t "new": "gt", 
 
\t \t "level": "typeone" 
 
\t }] 
 
}]; 
 

 
console.log(containsString(arr, "typeone")); // contains "typeone" --> true \t 
 

 
function containsString(arr, strSearch) { 
 
\t var same = false; 
 
\t for (var p in arr) { 
 
\t \t var entry = arr[p]; 
 
\t \t var type = toString.call(entry); \t \t \t 
 
\t \t 
 
\t \t if (type.indexOf("Object") > -1 ? true : type.indexOf("Array") > -1 ? true : false) { 
 
\t \t \t return containsString(entry, strSearch); 
 
\t \t } else { 
 
\t \t \t same = (entry === strSearch); 
 
\t \t \t if (same) return same; 
 
\t \t } 
 
\t } // end for loop 
 
\t return same; 
 
}// end iterate