【问题标题】:How to check if an object exists within another object using JS如何使用JS检查一个对象是否存在于另一个对象中
【发布时间】:2017-11-19 22:55:29
【问题描述】:

假设我有一个对象数组

var arr= [{name:'John', lastName:'Smith', age:25}, {name:'Steve', lastName:'Johnson', age:56}];
var obj1 ={name:'John', lastName:'Smith'};

如何使用JS检查一个对象是否存在于另一个对象中?

嵌套循环能解决问题吗?第一个循环遍历数组内的对象,第二个循环遍历对象内的键/值对并将它们与 obj1 键/值对进行比较?有一个更好的方法吗 ?还是我应该使用 3 个循环?

函数应该返回包含 obj1 的 arr 中的 obj el。例如: arr[0] 应该返回,因为它包含 obj1

function objInArr(srcArr, obj) {

  var arr = [];

  //var srcLength = 0; 
  //var sourceSize = Object.keys(source).length; // The length of the source obj
  srcArr.forEach(function(el) {

    el.forEach(function(objEl){
      obj.forEach(function(sourceEl){
         if( sourceEl === objEl) { arr.push(sourceEl); }
      });
    });
  });

  return arr;
}

【问题讨论】:

    标签: javascript


    【解决方案1】:

    您可以结合使用 Arry#find()Array#some() 方法来循环遍历数组对象并查找是否存在具有相同键和值的对象,或者不是:

    var exists = arr.find(function(o){
        return Object.keys(o).some(function(k){
              return !Object.keys(obj1).indexOf(k)>-1 || o[k]!=obj1[k];
        });
    });
    

    如果存在,它将返回一个object,如果你想返回一个boolean,你可以将.find()更改为.some()

    如果一个对象没有迭代的 key 或者它的 value 不一样,则语句 !Object.keys(obj1).indexOf(k)>-1 || o[k]!=obj1[k] 将退出。

    演示:

    var arr= [{name:'John', lastName:'Smith', age:25}, {name:'Steve', lastName:'Johnson', age:56}];
    var obj1 ={name:'John', lastName:'Smith'};
    
    var exists = arr.find(function(o){
        return Object.keys(o).some(function(k){
              return !Object.keys(obj1).indexOf(k)>-1 || o[k]!=obj1[k];
        });
    });
    
    console.log(exists);

    【讨论】:

      【解决方案2】:
      // object contains subObject
      function partialContains(object, subObject) {
          // Create arrays of property names
          const objProps = Object.getOwnPropertyNames(object);
          const subProps = Object.getOwnPropertyNames(subObject);
      
          if (subProps.length > objProps.length) {
              return false;
          }
      
          for (const subProp of subProps) {
              if (!object.hasOwnProperty(subProp)) {
                  return false;
              }
      
              if (object[subProp] !== subObject[subProp]) {
                  return false;
              }
          }
      
          return true;
      }
      

      您现在可以像这样使用它:

      const arr= [{name:'John', lastName:'Smith', age:25}, {name:'Steve', lastName:'Johnson', age:56}];
      
      const obj1 ={name:'John', lastName:'Smith'};
      
      const containing = arr.find((object) => partialContains(object, obj1));
      

      如果containing未定义,则没有找到,否则返回包含obj1的对象。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-06-05
        • 1970-01-01
        • 1970-01-01
        • 2019-11-26
        • 1970-01-01
        • 2021-06-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多