English 中文(简体)
如何过滤基于过滤物体的物体
原标题:How to filter an object based on a filter object

是否有一种方便的办法来过滤<条码>bigObject,其中只有<条码>中定义的特性> 过滤界面<> 目标作为产出?

大型物体有许多特性,我想将信息淡化到我需要的财产上(为节省某些地方,不希望/不能够拯救全部物体)。

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"
    }                
};
最佳回答

简言之,我期望的是:

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
问题回答

暂无回答




相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签