Listing keys containing a given string?

Data such as:

var people = [ 
    { 'myKey': 'John Kenedy', 'status': 1 },
    { 'myKey': 'Steeven Red', 'status': 0 },
    { 'myKey': 'Mary_Kenedy', 'status': 3 },
    { 'myKey': 'Carl Orange', 'status': 0 },
    { 'myKey': 'Lady Purple', 'status': 0 },
    ...                                       // thousands more
];

      

How to efficiently get a list of all objects contained in a myKey

string Kenedy

?

http://jsfiddle.net/yb3rdhm8/


Note: I am currently using str.search()

:

Search ("str") returns the position of the match. Returns -1 if no match was found.

do the following:

var map_partial_matches = function(object, str){
    var list_of_people_with_kenedy = [] ;
    for (var j in object) {
        if (object[j]["myKey"].search(str) != -1) { 
            object[j].presidentName = "yes";  // do something to object[j]
            list_of_people_with_kenedy.push({ "people": object[j]["myKey"] }); // add object key to new list  
        }
    } return list_of_people_with_kenedy;
}
map_partial_matches(people, "Kenedy");

      

I could do the same with str.match()

:

str.match()

returns matches as an Array object. Returns null

if no match was found.

It still works, but I have no idea if it is efficient or clears entirely.

+3


source to share


3 answers


You can write a basic function that uses filter

to return an array of matches based on key and value:

function find(arr, key, val) {
  return arr.filter(function (el) {
    return el[key].indexOf(val) > -1;
  });
}

var result = find(people, 'myKey', 'Kenedy');

      

Alternatively, use the usual one for...loop

:



function find(arr, key, val) {
  var out = [];
  for (var i = 0, l = arr.length; i < l; i++) {
    if (arr[i][key].indexOf(val) > -1) {
      out.push(arr[i]);
    }
  }
  return out;
}

      

DEMO

+1


source


You can use filter()

:

var filtered = people.filter(function (item) {

    if (item.myKey.indexOf("Kenedy") != -1) 
       return item;

});

      



You can also check out Sugar.js

+2


source


To find your unsorted object, you need to go through all of its properties. So I would say that a simple with loop indexOf

would be pretty much the best you can do:

var foundItems = [];
for(var i = 0; i < people.length ;i++)
{
    if(people[i].myKey.indexOf('Kenedy') > -1)
       foundItems.push(people[i]]);       
}

      

Maybe you can tweak it a bit, but this is pretty much the best you can get.

+2


source







All Articles