如何基于过滤器对象过滤对象

时间:2012-04-25 07:24:41

标签: javascript filter

是否有方便的方法来过滤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 个答案:

答案 0 :(得分: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