Reputation: 509
I have an array with keys like ["1", "5", "9"]
And I have an object with the same keys, something like this: selections: { "5": {}, "12": {} }
What is the easiest way to get a boolean
value out of it.
It should return true
if any of the keys in the array is present in my object.
I am using angular and lodash, is there any smart solution for this or do I need to do a loop for it? And if I do a loop, what is the most efficient way?
Upvotes: 2
Views: 90
Reputation: 25906
Array.prototype.some() executes the callback function once for each element present in the array until it finds one where callback returns a true value. If such an element is found, some() immediately returns true. Otherwise, some() returns false. Array.prototype.some() is in ECMAScript 1.5 and should work just about anywhere.
function compareArrayToObject(array, obj) {
return array.some(function (a) { return a in obj; });
}
var array = ["1", "5", "9"];
var obj = { "5": {}, "12": {} };
var result = compareArrayToObject(array, obj);
document.write(result);
Upvotes: 0
Reputation: 386550
Just a single line of code:
var array = ["1", "5", "9"],
obj = { "5": {}, "12": {} },
any = array.some(function (a) { return a in obj; });
document.write(any);
Upvotes: 1
Reputation: 6266
var keys = ["1", "5", "9"];
var selections = {"5": {}, "12": {}};
function hasAnyKey(keys, selections) {
for (var i = 0; i < keys.length; i++) {
if (selections[keys[i]]) {
return true;
}
}
return false;
};
hasAnyKey(keys, selections);
This solution will return as soon as there is 1 match, which equates to returning true when there is at least 1 match, which is what you want. In theory, this will work faster than the solutions with Array.prototype.filter
for larger inputs.
Upvotes: 0
Reputation:
var selections = { "5": {}, "12": {} };
var array = ["1", "5", "9"];
array.some(key => selections.hasOwnProperty(key));
Upvotes: 3
Reputation: 748
Did you try to use hasOwnProperty()?
function check() {
var selections = { "5": {}, "12": {} };
return ["1", "5", "9"].filter(function(value) {
return selections.hasOwnProperty(value);
}).length > 0;
}
Upvotes: 3