简体   繁体   English

将数组与键对比JavaScript对象中的键

[英]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": {} } 我有一个像["1", "5", "9"]这样的键的数组["1", "5", "9"]我有一个具有相同键的对象,如下所示: selections: { "5": {}, "12": {} }

What is the easiest way to get a boolean value out of it. 从中获取boolean值的最简单方法是什么? It should return true if any of the keys in the array is present in my object. 如果我的对象中存在数组中的任何键,它应该返回true I am using angular and lodash, is there any smart solution for this or do I need to do a loop for it? 我正在使用角度和lodash,有没有任何智能解决方案或我需要为它做一个循环? And if I do a loop, what is the most efficient way? 如果我做一个循环,最有效的方法是什么?

Did you try to use hasOwnProperty()? 你尝试使用hasOwnProperty()吗?

function check() {
  var selections = { "5": {}, "12": {} };
  return ["1", "5", "9"].filter(function(value) {
    return selections.hasOwnProperty(value);
  }).length > 0;
}
var selections = { "5": {}, "12": {} };
var array = ["1", "5", "9"];

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

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

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. 只要有1个匹配,此解决方案将立即返回,这相当于当至少有1个匹配时返回true,这就是您想要的。 In theory, this will work faster than the solutions with Array.prototype.filter for larger inputs. 从理论上讲,对于较大的输入,这将比使用Array.prototype.filter的解决方案更快。

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. Array.prototype.some()为数组中的每个元素执行一次回调函数,直到找到一个回调返回true值的元素。 If such an element is found, some() immediately returns true. 如果找到这样的元素,some()会立即返回true。 Otherwise, some() returns false. 否则,some()返回false。 Array.prototype.some() is in ECMAScript 1.5 and should work just about anywhere. Array.prototype.some()ECMAScript 1.5中 ,应该可以在任何地方工作。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM