dom
dom

Reputation: 509

Compare an array with keys to keys in an object JavaScript

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

Answers (5)

Stephen Quan
Stephen Quan

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

Nina Scholz
Nina Scholz

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

clocksmith
clocksmith

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

user5004821
user5004821

Reputation:

var selections = { "5": {}, "12": {} };
var array = ["1", "5", "9"];

array.some(key => selections.hasOwnProperty(key));

Upvotes: 3

Pavel Komiagin
Pavel Komiagin

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

Related Questions