开发者

Get JavaScript object's fields by string name pattern

I have JS object A like:

 { Name, NameFilter, NameType, ..., Desc, DescName, DescType, ... }

I want to build new o开发者_开发百科bject B by next rule:

If A contains field AbcFilter, then B.Abc = { value: A.Abc, filter: A.AbcFilter, type: A.AbcType} for each AbcFilter in A.

In other words, I want to iterate over the members of JS object and get only members, which name contains any string and get the field value by it's string name.


Just iterate normally and check whether the property name contains 'Filter':

var B = {}, i, prefix;

for(var prop in A) {
    if(A.hasOwnProperty(prop)) {
        i = prop.indexOf('Filter');
        if(i > -1) {
            prefix = prop.substr(0, i);
            B[prefix] = {
                value: A[prefix],
                filter: A[prop],
                type: A[prefix+'Type']
            };
        }
    }
}

Of course this works only under the assumption that 'Filter' is not contained in other property names.

Reference: String.prototype.indexOf, String.prototype.substr

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜