Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an object's properties represent a super set of another object?

Suppose we have 2 objects:

var foo = {
       a: 3,
       b: 'yellow',
       c: {
           d: 5,
           e: 'green'
       }
    },
    bar = {
       b: 'yellow',
       c: {
           d: 5,
           e: 'green'
       }
    };

What is the best way to check that foo contains bar?

I am already using Lodash in my application, so you can use functions from that library if it makes it easier. Otherwise, vanilla JS is fine.

[EDIT]

Well, let me try to explain what I mean when I use term 'contain'. I will do it in LoDash terminology.

LoDash has _.extend method, so that if have 2 objects:

var obj1 = {a:1, b:2}, 
    obj2 = {b:4, c:{d:'green', e:5}}

then the operation _.extend(obj1, obj2) will 'extend' obj1 - it will now have the value

{a:1, b:4, c:{d:'green', e:5}} 

i.e. obj1 'contains' obj2 now.

like image 601
Alexey Avatar asked Oct 23 '25 03:10

Alexey


2 Answers

_.isMatch(foo, bar) does the job.

https://lodash.com/docs/4.17.15#isMatch

like image 91
Emre Tapcı Avatar answered Oct 25 '25 18:10

Emre Tapcı


@GregL gave a working solution for the question. It works for me. But I found similar more concise solution, so I decided to reveal it:

_.some([foo], bar)
like image 24
Alexey Avatar answered Oct 25 '25 17:10

Alexey