Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if two javascript objects have the same fields?

Tags:

javascript

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.


1 Answers

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);
}
like image 193
JLRishe Avatar answered Mar 22 '26 23:03

JLRishe