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

Bri*_*lip 5 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
Run Code Online (Sandbox Code Playgroud)

Jas*_*zun 1

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

    for (i=0; i<collection.length; i++) {
        var matches = true;
        for (var prop in source) {
            if (!collection[i].hasOwnProperty(prop) || collection[i][prop] !== source[prop]) {
                matches = false;
                break;
            }
        }
        if (matches) {
            result.push(collection[i]);
        }
    }
    return result;
}
Run Code Online (Sandbox Code Playgroud)

基本上,您必须检查所有属性并确保它们匹配,然后才其添加到result数组中。