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 fieldAbcFilter
, 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
精彩评论