2012-04-25 226 views
1

是否有一種方便的方法來過濾bigObject只有在filterInterface中定義的屬性才能獲得filteredObject作爲輸出?如何根據過濾器對象過濾對象

大對象有很多屬性,我想剝離信息到我需要的屬性(將它保存到某處,不想/不能保存完整的對象)。

I prepared the following code as a jsfiddle here.

// My big object 
var bigObject = { 
    prop1: { 
     prop2: { 
      prop3: 123, 
      prop4: 456, 
      prop5: "TEST"    
     }, 
     prop6: 789, 
     prop7: "xxx" 
    }, 
    prop8: 5.6, 
    prop9: 3  
}; 

// My "interface" to filter the object 
var filterInterface = { 
    prop1: { 
     prop2: { 
      prop3: true, 
     }, 
     prop7: true 
    }     
}; 

// My expected result, only the properties of 
// big Object which match the interface 
var filteredObject = { 
    prop1: { 
     prop2: { 
      prop3: 123, 
     }, 
     prop7: "xxx" 
    }     
}; 

回答

1

簡單地說,我希望是這樣的:

var filteredObject = {} 

for (var key in filterObject) { 
    if (bigObject.hasOwnProperty(key)) { 
    filteredObject[key] = bigObject[key]; 
    } 
} 

包括遞歸,如果你想 「深」 過濾:

function filter(obj, filterObj) { 
    var newObj = {}; 

    for (var key in filterObj) { 

    if (obj.hasOwnProperty(key)) { 

     if (typeof obj[key] == 'object' && typeof filterObj[key] == 'object') { 
     newObj[key] = filter(obj[key], filterObj[key]); 

     } else { 
     newObj[key] = obj[key]; 
     } 
    } 
    } 
    return newObj; 
} 


var o = filter(bigObject, filterInterface); 

alert(o.prop1.prop7); // 'xxx' 
alert(o.prop1.prop9); // undefined 
+0

完美,完蛋了。謝謝! – Marc 2012-04-25 09:07:13