0

I should compare existing all fields and values from object1 in object2

example:

object1: {
  user: {
    id: 25,
    name: "Elon"
  }
};

object2: {
  user: {
    id: 25,
    name: "Elon",
    role: "admin"
  },
  rules: [
    "edit"
  ]
}

compareFn(object1, object2); //true

I can write this function, but I think that it exist in some testing framework, but I have not found :(

Can you help me? Thx!

Jackson
  • 884
  • 2
  • 13
  • 22
  • Maybe this?: https://stackoverflow.com/questions/1068834/object-comparison-in-javascript – Dani May 22 '18 at 15:09
  • this is deepEqual, but in my version comparing: {a: 5} and {a: 5, b: 10} should be true – Jackson May 22 '18 at 15:14
  • and I dont want to provide self solutions. Testing frameworks have this function. assert.deepEqual, or should.deepEqual. I want to use existing solution in my happening – Jackson May 22 '18 at 15:19
  • Jest has an objectContaining method that should do what you need. It is explained here: https://medium.com/@boriscoder/the-hidden-power-of-jest-matchers-f3d86d8101b0 – Steve Vaughan May 22 '18 at 15:25
  • Yeah, it's true... above link is not for your case – Dani May 22 '18 at 15:25

1 Answers1

0

The test framework Jest would allow you do achieve this. Using their toMatchObject assertion. Your code would look like:

const object1 = {
  user: {
    id: 25,
    name: "Elon"
  }
};

const object2 = {
  user: {
    id: 25,
    name: "Elon",
    role: "admin"
  },
  rules: [
    "edit"
  ]
}

test('object1 found within object2', () => {
    expect(object2).toMatchObject(object1);
});

Documentation: https://facebook.github.io/jest/docs/en/expect.html#tomatchobjectobject

Steve Vaughan
  • 2,163
  • 13
  • 18