0

these are my two objects

     var obj1={"firstName":"john","lastName":"Peter","email":"rasheed@gmail.com"}
var obj2={"firstName":"john","lastName":"Peter","email":"rasheed@gmail.com","address":"New York"}

obj1 comes dynamically we dont know what comes in that first as property, i want to return true if obj1 properties exist in obj2 properties along with values, and if any one object properties with its value doest not exist in obj2 then it should retrun false, how to do this, do you guys have any idea?

Syed Rasheed
  • 559
  • 2
  • 10
  • 29
  • 1
    Look into this post - http://stackoverflow.com/questions/201183/how-do-you-determine-equality-for-two-javascript-objects – Dev Shangari Sep 23 '15 at 11:07
  • Thanks i got it this is the answer `var stooge = {name: 'moe', age: 32}; _.isMatch(stooge, {age: 32}); => true` – Syed Rasheed Sep 23 '15 at 11:13

2 Answers2

0

You could use libraries like lodash to do it, but if you want a simple and easy answer, you could do this(not working on ie8 because of "Object.keys"):

var equal = true;
if(Object.keys(obj1).length == Object.keys(obj2).length)
  for(i in obj1){
    if(typeof(obj2[i]) == 'undefined') equal = false;
  }
else equal = false;
console.log(equal);
Ismael Fuentes
  • 240
  • 1
  • 10
0

Mash the two objects together and see if the result equals the one you're checking against:

function check(obj1, obj2){
    var obj3 = angular.extend({}, obj2, obj1);

    return angular.equals(obj3, obj2);
}

JSfiddle showing result: http://jsfiddle.net/0p59ya5a/

var obj1={"firstName":"john","lastName":"Peter","email":"rasheed@gmail.com"}
var obj2={"firstName":"john","lastName":"Peter","email":"rasheed@gmail.com","address":"New York"}

console.log(check(obj1, obj2)); //true

var obj3={"firstName":"john","lastName":"Peter","email":"rasheed@gmail.com"}
var obj4={"firstName":"john","lastName":"Peter","address":"New York"}

console.log(check(obj3, obj4)); //false

var obj1={"firstName":"john","lastName":"Peter","email":"rasheed@gmail.com"}
var obj2={"firstName":"jim","lastName":"Peter","email":"rasheed@gmail.com","address":"New York"}

console.log(check(obj5, obj6)); //false
Mathew Berg
  • 28,625
  • 11
  • 69
  • 90