Skip to content

Instantly share code, notes, and snippets.

@esson
Last active January 22, 2016 11:08
Show Gist options
  • Save esson/33c86c7ebe613f8a4584 to your computer and use it in GitHub Desktop.
Save esson/33c86c7ebe613f8a4584 to your computer and use it in GitHub Desktop.
Returns a dictionary object with keys for each value in the provided object and its descendants/children. Keys are in the style of ASP.NET, i.e. "propertyName.collection[3]".
module AspNetUtilities {
export interface IAspNetFormValueDictionary {
[key: string]: any;
}
function collectAspNetFormKeyValues(keyPrefix: string, source: Object, dictionary: IAspNetFormValueDictionary) {
var localKeyPrefix = '';
if (Object.prototype.toString.call(source) === '[object Array]') {
var objArray = <any[]>source;
for (var i = 0; i < objArray.length; i++) {
localKeyPrefix = keyPrefix + '[' + i + ']';
if (typeof objArray[i] === 'object') {
collectAspNetFormKeyValues(localKeyPrefix, objArray[i], dictionary);
} else {
dictionary[localKeyPrefix] = objArray[i];
}
}
} else {
if (typeof source === 'object') {
for (var prop in source) {
if (source.hasOwnProperty(prop)) {
localKeyPrefix = keyPrefix ? keyPrefix + '.' + prop : prop;
if (typeof source[prop] === 'object') {
collectAspNetFormKeyValues(localKeyPrefix, source[prop], dictionary);
} else {
dictionary[localKeyPrefix] = source[prop];
}
}
}
}
}
return dictionary;
}
export function getAspNetFormKeyValues(source: Object) {
var dictionary: IAspNetFormValueDictionary = {};
if (typeof source === 'undefined') {
return;
}
if (typeof source === 'object') {
collectAspNetFormKeyValues('', source, dictionary);
} else {
dictionary['value'] = source;
}
return dictionary;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment