Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if literal object included in other object with Built-in API

I mean Object-B is included in Object-A, when all attributes of Object-B are included in the object-A and its values are the same in the object-A.

 var obj_b={a:1,d:3}
 var obj_a={a:1,b:22,c:33,d:3} //--> obj_b includes in obj_a
 var obj_c={a:1,f:4};

isIncluded=(small,big)=>Object.keys(small).every((k)=>big[k] === small[k])
console.log(
 'Does "obj-b" included in "obj-a"  ? ',isIncluded(obj_b,obj_a)   
)
console.log(
 'Does "obj-c" included in "obj-a"  ? ',isIncluded(obj_c,obj_a)   
)

My question is:

Does ES6/ES7 has built-in API more elegant and brief for that?

For example, to extend object from origin, ES6 brought Object.assign(o1,o2)?

Is there something like Object.isInclude(o1,o2)?

like image 944
Abdennour TOUMI Avatar asked Jul 30 '16 11:07

Abdennour TOUMI


People also ask

How do you know if an object is literal?

There is no way to tell the difference between an object built from an object literal, and one built from other means. It's a bit like asking if you can determine whether a numeric variable was constructed by assigning the value '2' or '3-1';

How do you check if an object has any property?

The hasOwnProperty() method will check if an object contains a direct property and will return true or false if it exists or not. The hasOwnProperty() method will only return true for direct properties and not inherited properties from the prototype chain.

How do you check if an object has any keys?

Using the Object.Object. keys() is a static method that returns an Array when we pass an object to it, which contains the property names (keys) belonging to that object. We can check whether the length of this array is 0 or higher - denoting whether any keys are present or not.

How do you check if all object values are true?

To check if all values in object are equal to true :Use the Object. values() method to get an array of the object's values. Call the every() method on the array. The every method will test if all values in the array are equal to true and will return the result.


1 Answers

No, there is not. Your solution is already brief and elegant, although it could be golfed by another 4 characters.

const isSubObject = (small,big)=>Object.keys(small).every(k=>big[k]===small[k]);
like image 187
Bergi Avatar answered Nov 01 '22 01:11

Bergi