javascript Javascript实用程序函数来比较2个对象。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript Javascript实用程序函数来比较2个对象。相关的知识,希望对你有一定的参考价值。

function logDifference(arr1, arr2) {

    let difference = arr1.filter(
        x => arr2.indexOf(x) == -1)
        .concat(arr2.filter(
            x => arr1.indexOf(x) == -1)
        );

    if (difference.length < 1) return []; // if no difference return empty array
    return difference;
    console.log(difference)

};

function areObjectsSimilar(obj1, obj2) {
    
    const differences = [];
    
    const obj1Keys = Object.keys(obj1);
    const obj2Keys = Object.keys(obj2);
    
    const obj1Length = obj1Keys.length;
    const obj2Length = obj2Keys.length;
    
    
    // check if equal number of properties
    if(obj1Length !== obj2Length) {
      differences.push(`Not equal number of properties`);
    }

    const differentProps = logDifference(obj1Keys, obj2Keys);

    if(differentProps.length > 0) differences.push(`These properties exist only in one of the objects: ${differentProps.join()}`);
    
    // determine which object should be the sample
    function whichLonger(first, second) {
      const firstLength = Object.keys(first).length;
      const secondLength = Object.keys(second).length;
      
      if(firstLength > secondLength) return first;
      if(secondLength > firstLength) return second;
      return first
    }
    
    
    const sampleObject = whichLonger(obj1, obj2);
    const sampleKeys = Object.keys(sampleObject);
    
    // comapre value of each
    sampleKeys.forEach((key) => {
      if(obj1[key] == obj2[key]) {
        // console.log(`SIMILAR: ${key} for both are the same`);
      } else {
        console.log(`DIFFERENT: ${obj1.constructor.name}'s ${key} is ${obj1[key]} while second object's ${key} is ${obj2[key]}`);
        differences.push(`DIFFERENT: first object's ${key} is ${obj1[key]} while second object's ${key} is ${obj2[key]}`)
      }
      
    });
    
    if(differences.length > 0) {
      console.log(`OBJECTS DO NOT HAVE EQUAL PROPERTIES. LIST OF DIFFERENCES: \n ${differences.join('\n\n')}`);
      return false
    } else {
      console.log('objects have equal properties')
      return true
    }
    
    
  };

export default areObjectsSimilar;

以上是关于javascript Javascript实用程序函数来比较2个对象。的主要内容,如果未能解决你的问题,请参考以下文章

javascript Javascript实用程序函数来比较2个对象。

javascript 我个人的JavaScript实用程序函数集(ES6)

javascript 到 actionscript 按键传递实用程序?

有没有办法从 javascript 运行命令行实用程序? [复制]

javascript 实用程序设置

javascript 浏览器JS实用程序