javascript - 检查对象数组中的任何对象是否包含另一个对象中的所有键/值对

标签 javascript javascript-objects

我正在尝试编写一个函数来查看对象数组(第一个参数)并返回包含给定对象的所有键/值对的所有对象的数组(第二个参数)。

只有当 source 对象(第二个参数)包含一个键/值对时,我下面的代码才有效。当 source 对象有两个或多个键/值对时,结果不是预期的。

如何在 source 对象中考虑多个键/值对?

function findObjects(collection, source) {
  var result = [];

  for (i=0; i<collection.length; i++) {
    for (var prop in source) {
      if (collection[i].hasOwnProperty(prop) && collection[i][prop] == source[prop]) {
        console.log('Collection\'s object ' + [i] + ' contains the source\'s key:value pair ' + prop + ': ' + source[prop] + '!');
        result.push(collection[i]);
      } else {
        console.log('fail');
      }
    }
  }

  console.log('The resulting array is: ' + result);
  return result;
}

findObjects([{ "a": 1, "b": 2 }, { "a": 1 }, { "b": 2, "c": 2 }], { "a": 1, "b": 2 });

// only the first object should be returned since it contains both "a":1 and "b":2

最佳答案

你可以使用一些数组方法,比如 Array#map

The map() method creates a new array with the results of calling a provided function on every element in this array.

Array#every

The every() method tests whether all elements in the array pass the test implemented by the provided function.

并首先使用 Object.keys 获取源的属性.

The Object.keys() method returns an array of a given object's own enumerable properties, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

function findObjects(collection, source) {
    var keys = Object.keys(source);          // get all properties of source
    return collection.filter(function (c) {  // filter collection
        return keys.every(function (k) {     // check every key
            return c[k] === source[k];       // compare value of collection and source
        });
    });
}

console.log(findObjects([{ "a": 1, "b": 2 }, { "a": 1 }, { "b": 2, "c": 2 }], { "a": 1, "b": 2 }));

在 ES6 语法中相同(阅读更多:Arrow functions)

Basically this style is a short writing of

function (x) { return y; }

became

          x =>        y

function findObjects(collection, source) {
    const keys = Object.keys(source);
    return collection.filter(c => keys.every(k => c[k] === source[k]));
}

console.log(findObjects([{ "a": 1, "b": 2 }, { "a": 1 }, { "b": 2, "c": 2 }], { "a": 1, "b": 2 }));

关于javascript - 检查对象数组中的任何对象是否包含另一个对象中的所有键/值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37845249/

相关文章:

javascript - 无法检索有效的 WinSAT 评估。控制台

javascript - 将用户输入作为选项保存到代码中 - Google Chrome 扩展

javascript - 在 Javascript 中使用 Jinja2 模板的最佳方式?

javascript - 在不指定纬度和经度的情况下将谷歌地图置于地点 ID 的中心?

javascript - 使用函数参数访问 JavaScript 中的对象

javascript - 将数组中的所有键值推送到新数组中,只要不同键的值(在同一对象中)满足特定条件

javascript - 在页面加载时删除 CSS 模态闪光

javascript - 当满足某些条件时,如何获取数组的长度?

javascript - 如何从异步回调函数返回值?

javascript - 如何从异步回调函数返回值?