There is a function that looks for value in the object. How can you make it so that you can search by key?

For example now it works like this:

when the search('r', items) function has an argument r m, it will produce words where there is r .

// ["bar", "lorem", "dolor"]

And it would be nice if you could search by keys. For example:

if the argument is foo , should output: // ["bar", "lorem", "dolor"]

and if the bar argument should ["amet","ipsum","dolor"] : ["amet","ipsum","dolor"]

whole function:

 function search(s, arr) { var matches = []; for (var i = arr.length; i--;) { for (key in arr[i]) { if (arr[i].hasOwnProperty(key) && arr[i][key].indexOf(s) > -1) matches.push(arr[i][key]); } } return matches; }; var items = [{ "foo": "bar", "bar": "sit" }, { "foo": "lorem", "bar": "ipsum" }, { "foo": "dolor", "bar": "amet" }]; search('r', items); // ["bar", "lorem", "dolor"] 

  • one
    And what is the difficulty then. You already have a key in the loop and check it for equality of the argument - Mike

1 answer 1

Similarly, the same:

 function search(s, arr) { var matches = []; for (var i = arr.length; i--;) { for (key in arr[i]) { if (arr[i].hasOwnProperty(key) && key.indexOf(s) > -1) { matches.push(arr[i][key]); } } } return matches; }; var items = [{ "foo": "bar", "bar": "sit" }, { "foo": "lorem", "bar": "ipsum" }, { "foo": "dolor", "bar": "amet" }]; search('foo', items);