我们如何仅在js

时间:2018-01-16 17:41:48

标签: javascript

我有2个对象 a b 我想仅比较相同键对象的数据

var a = {name1:'alisha',age:18,subject:{main:'javascript',major:'maths'}};
var b = {name1:'alisha',age:'18'};

 function compareData(a,b){
  return JSON.stringify(a) == JSON.stringify(b); 
 }

 console.log(compareData(a,b))

这是比较所有键但我想只比较可用键的可用数据我该怎么做

2 个答案:

答案 0 :(得分:2)

您可以将其用于浅层比较:

// Returns true if the values are equal (shallow)
// for all properties that both objects have
function compareData(a,b){
  return Object.keys(a).filter( k => k in b ).every( k => a[k] === b[k] );
}

它将为您的对象返回false,因为其中一个具有年龄的数字而另一个具有字符串。对于这些对象,它将返回true:

var a = {name1:'alisha',age:18,subject:{main:'javascript',major:'maths'}};
var b = {name1:'alisha',age:18};

示例:



console.log( compareData( {}, {age: 5} ) ); // true (no shared properties)
console.log( compareData( {age: 5}, {age: 5} ) ); // true (equal shared properties)
console.log( compareData( {age: 4}, {age: 5} ) ); // false

var a = {name1:'alisha',age:18,subject:{main:'javascript',major:'maths'}};
var b = {name1:'alisha',age:18};

console.log( compareData( a, b ) ); // true

function compareData(a,b){
  return Object.keys(a).filter( k => k in b ).every( k => a[k] === b[k] );
}




答案 1 :(得分:1)

循环显示第一个项目键并检查是否:
  他们存在   2.值是相同的

似乎工作:



var a = { name1:'alisha', age:18,subject:{main:'javascript',major:'maths'}};
var b = { name:'alisha', age: 19 };

function areTheSame(a,b){
  // fat arrow function returns true if any element has a difference
  return !Object.keys(a).some(key => {
    if(b.hasOwnProperty(key)){
      return a[key] !== b[key];
    }
    return false;
  });
}

console.log(areTheSame(a,b))