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:
- the object b have more keys object a, , true.
- 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
Post a Comment