javascript - How to know if an object includes another one -


i trying find library able if object b includes property , values of object (and not opposite !).

it means 2 things librairies found not handle:

  1. the object b have more keys object a, , true.
  2. the object b have more items in arrays object a, , true.

this method _.difference() of lodash does, items in arrays.

i found interesting libraries deep-diff, need.

i code doing job, convinced other peoples met need before.

here example 2 objects:

var = {   name: 'toto',   pets: [ { name: 'woof', kind: 'dog' } ] };  var b = {   name: 'toto',   pets: [ { name: 'gulp', kind: 'fish' }, { name: 'woof', kind: 'dog' } ],   favoritecolor: 'blue' }; 

here, includes b since can find in b every properties , values of a. librairies diff no, since not first second item of "pets" equal a, , b has additionnal property "favoritecolor".

do know librairy able kind of comparison?

you use modified version of deepcompare linked in comments. need past keys length comparison, seems.

// b has of  function deephas(a, b) {    if (typeof !== typeof b) {      return false;    }    if (typeof !== 'object') {      return === b;    }      // may need polyfill array higher-order functions here    if(array.isarray(a) && array.isarray(b)) {      return a.every(function(av) {        return b.indexof(av) !== -1;      });    }        if (object.keys(a).length > object.keys(b).length) {      return false;    }    (var k in a) {      if (!(k in b)) {        return false;      }      if (!deephas(a[k], b[k])) {        return false;      }    }    return true;  }      var a1 = {    foo: ['a', 'b', 'c'],    bar: 'bar',    baz: {      baz: {        baz: 'wee'      }    }  };    var b1 = {    foo: ['a', 'b', 'c', 'd'],    bar: 'bar',    baz: {      baz: {        baz: 'wee',        whatever: 'wat'      }    },    ok: 'test'  };    console.log('b1 has of a1', deephas(a1, b1));    var a2 = {    foo: ['a', 'b', 'c'],    bar: 'bar',    baz: {      baz: {        baz: 'wee'      }    }  };    var b2 = {    foo: ['a', 'b', 'c'],    baz: {      baz: {        baz: 'wee'      }    }  };    console.log('b2 not have of a2', !deephas(a2, b2));    console.log('["a","b"] has ["b"]', deephas(["b"], ["a","b"]));    console.log('{foo: ["a","b"]} has {foo: ["b"]}', deephas({ foo: ["b"] }, { foo:["a","b"] }));


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -