簡體   English   中英

JavaScript:比較兩個 JSON 對象的結構而忽略它們的值

[英]JavaScript: Compare the structure of two JSON objects while ignoring their values

我使用基於 Node.js 的模擬服務器來指定和模擬來自后端的 API 響應。 如果后端和前端都符合規范,那么進行某種檢查將非常有幫助。 為了做到這一點,我需要某種方法來比較兩個 JSON 對象的結構。

例如,這兩個對象應該被認為是相等的:

var object1 = {
    'name': 'foo',
    'id': 123,
    'items' : ['bar', 'baz']
}

var object2 = {
    'name': 'bar',
    'items' : [],
    'id': 234
}

任何想法我會怎么做?

這是一個優雅的解決方案。 你可以像這樣簡單地做:

var equal = true;
for (i in object1) {
    if (!object2.hasOwnProperty(i)) {
        equal = false;
        break;
    }
}

如果兩個元素具有相同的屬性,則 var equal必須保持為true

並作為功能:

function compareObjects(object1, object2){
    for (i in object1)
        if (!object2.hasOwnProperty(i))
            return false;
    return true;
}

您可以使用hasOwnProperty函數執行此操作,並檢查 object1 的每個屬性名稱是否在 object2 中:

function hasSameProperties(obj1, obj2) {
  return Object.keys(obj1).every( function(property) {
    return obj2.hasOwnProperty(property);
  });
}

演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM