简体   繁体   English

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

[英]How to filter an object based on a filter object

Is there a convenient way to filter bigObject with only the properties defined in filterInterface to get filteredObject as output? 是否有一种简便的方法来仅使用filterInterface定义的属性来过滤bigObject ,以将filteredObject作为输出?

The big object has a lot of properties and I want to strip the information down to the properties I need (to save it somewhere, don't want to/can't save the complete object). 大对象具有很多属性,我想将信息分解为所需的属性(将其保存在某个地方,不想/不能保存整个对象)。

I prepared the following code as a jsfiddle here. 我在这里准备了以下代码作为jsfiddle。

// 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"
    }                
};

Briefly, I'd expect something like: 简要地说,我希望这样的事情:

var filteredObject = {}

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

Include recursion if you want "deep" filtering: 如果要“深度”过滤,请包括递归:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM