Skip to content

Instantly share code, notes, and snippets.

@xujiesh0510
Last active March 25, 2022 09:32
Show Gist options
  • Save xujiesh0510/96fb67c4c5b31996cf4cdc0d692e6519 to your computer and use it in GitHub Desktop.
Save xujiesh0510/96fb67c4c5b31996cf4cdc0d692e6519 to your computer and use it in GitHub Desktop.
Convert javascript complex object to ASP.NET Web Api Get Method
// Usage:
// var parser = new ApiHttpGetModelParser();
// var result = parser.parseApiGetModel({id:1,arr:[1,2,3]}); // suit web api
// result is {"id":1,"arr[0]":1,"arr[1]":2,"arr[2]":3}
function ApiHttpGetModelParser() {
var self = this;
var results = [];
var arrayType = "[object Array]";
var objectType = "[object Object]";
var isWebApiSimpleType = function (value) {
var propType = Object.prototype.toString.call(value);
if ([arrayType, objectType].indexOf(propType) < 0) {
return true;
}
return false;
};
var getLeafPathAndValue =
function (prefix, propValue) {
var path = prefix;
if (isWebApiSimpleType(propValue)) {
results.push({ path: path, value: propValue });
return;
}
var propType = Object.prototype.toString.call(propValue);
if (propType == arrayType) {
for (var t = 0; t < propValue.length; t++) {
var newPrefix = "[" + t + "]";
if (isWebApiSimpleType(propValue[t])) {
results.push({ path: path + newPrefix, value: propValue[t] });
}
else {
getLeafPathAndValue(path + newPrefix, propValue[t]);
}
}
}
else if (propType == objectType) {
for (var prop in propValue) {
var newPrefix = path == "" ? prop : ("." + prop);
if (!propValue.hasOwnProperty(prop)) {
continue;
}
if (isWebApiSimpleType(propValue[prop])) {
results.push({ path: path + newPrefix, value: propValue[prop] });
}
else {
getLeafPathAndValue(path + newPrefix, propValue[prop]);
}
}
}
};
self.parseApiGetModel = function (query) {
var queryStr = JSON.stringify(query);
var model = JSON.parse(queryStr);
getLeafPathAndValue("", model);
var obj = {
};
for (var i = 0; i < results.length; i++) {
var item = results[i];
obj[item.path] = item.value;
}
return obj;
}
}
@xujiesh0510
Copy link
Author

hope it works for you guys

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment