1

I have a json array that i have added in this way

var all_routes = [];

var entry = {
    'name':routeName,
    'title':routeTitle,
    'icon':routeIcon
  };

all_routes.push(entry);

I want to only return the arrays that match a specific string. I have this fiddle https://jsfiddle.net/codebreaker87/36mwbd2k/3/

I want to return the arrays that contain that specific string for iteration.

  • You mean you want to filter the objects in an array based on a string in one of the keys? – epascarello Dec 12 '16 at 12:29
  • [{'name':'jane doe','title':'hello world', 'icon':'cog.png'},{'name':'job doe','title':'mhello the world','icon':'thecog.png'}].filter(function(e){return e.name.indexOf('jane') !== -1}) – Lain Dec 12 '16 at 12:29

5 Answers5

1

You could filter with 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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Maybe just this:

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;
         }
      }  
    }
}
Rafał R
  • 241
  • 2
  • 10
0

If you are open to use libraries you could use lodash to solve it. Look here https://lodash.com/docs/4.17.2#find

Otherwise you have to go Rafal R:s way.

hesa
  • 451
  • 1
  • 4
  • 9
0

try this

var filtered = json_array.filter(function(val){return val.name.indexOf('doe') != -1})
Akshay
  • 815
  • 7
  • 16
0

You could loop through the all_routes array and check for the correct field value.

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;
}

And you can use it like so.

var matches = getMatches(all_routes, "name", "searchvalue");
NtFreX
  • 10,379
  • 2
  • 43
  • 63