我有一个以这种方式添加的json数组
var all_routes = [];
var entry = {
'name':routeName,
'title':routeTitle,
'icon':routeIcon
};
all_routes.push(entry);
我想只返回与特定字符串匹配的数组。我有这个小提琴https://jsfiddle.net/codebreaker87/36mwbd2k/3/
我想返回包含该特定字符串的数组以进行迭代。
答案 0 :(得分:1)
您可以使用String#indexOf
进行过滤。
function isPresent(property, value) {
return function (item) {
return item[property].indexOf(value) !== -1;
};
}
var json_array = [{ name: 'jane doe', title: 'hello world', icon: 'cog.png' }, { name: 'job doe', title: 'mhello the world', icon: 'thecog.png' }],
filtered = json_array.filter(isPresent('name', 'jane'));
console.log(filtered);
答案 1 :(得分:0)
也许只是这个:
for (var i=0; i < all_routes.length; i++) {
var json = all_routes[i];
for (var prop in json) {
if (json.hasOwnProperty(prop) {
if (//your statement to check if string is matched) {
//example
//json[prop].indexOf('foo') !== 1
return json;
}
}
}
}
答案 2 :(得分:0)
如果您愿意使用库,可以使用lodash来解决它。看这里https://lodash.com/docs/4.17.2#find
否则你必须去Rafal R:s。
答案 3 :(得分:0)
试试这个
var filtered = json_array.filter(function(val){return val.name.indexOf('doe') != -1})
答案 4 :(得分:0)
您可以遍历all_routes
数组并检查正确的字段值。
function getMatches(arrayToSearch, fieldName, fieldValue)
var foundEntries = [];
for(var i = 0; i < arrayToSearch.length; i++)
{
if(arrayToSearch[i][fieldName] === fieldValue)
{
foundEntries.push(arrayToSearch[i]);
}
}
return foundEntries;
}
你可以像这样使用它。
var matches = getMatches(all_routes, "name", "searchvalue");