Given:
I have the following two variables in Javascript:
var x = {
dummy1: null
dummy2: null
};
// Return true
var y = {
dummy1: 99,
dummy2: 0
}
// Return false
var y = "";
// Return false
var y = {
dummy1: null
};
// Return false
var y = {
dummy1: null,
dummy2: null,
dummy3: 'z'
}
// Return false
var y = null;
// Return false
var y = ""
Can anyone suggest to me how I can check if object x has the same field names as y ? Note that I am not checking the values of the parameters.
There are probably better names for these functions, but this should do it:
function hasAllProperties(subItem, superItem) {
// Prevent error from using Object.keys() on non-object
var subObj = Object(subItem),
superObj = Object(superItem);
if (!(subItem && superItem)) { return false; }
return Object.keys(subObj).every(function (key) {
return key in superObj;
});
}
function allPropertiesShared(x, y) {
return hasAllProperties(x, y) &&
hasAllProperties(y, x);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With