var newsearchdata = {
companyIdList: JSON.parse($("#newSearchCompanyListID").val())
}
I am parsing JSON array, if the value is null also request the api.
var newsearchdata = {
companyIdList: JSON.parse($("#newSearchCompanyListID").val())
}
I am parsing JSON array, if the value is null also request the api.
You have bunched up a lot of actions into a single line. Is there some reason you don't create a function that ALWAYS returns a clean value?
For example:
var newsearchdata = {
companyIdList: parseData()
}
function parseData() {
try {
const val = JSON.parse($("#newSearchCompanyListID").val())
const defaultBackup = whateveruwant
return val ? val : defaultbackup
} catch (e) {
return variable that works
}
}
Note:
JSON.parse handles null values. See here:
JSON.parse allows null as value https://tc39.es/ecma262/#sec-json-object
24.5.1 JSON.parse ( text [ , reviver ] ) The parse function parses a JSON text (a JSON-formatted String) and produces an ECMAScript value. The JSON format represents literals, arrays, and objects with a syntax similar to the syntax for ECMAScript literals, Array Initializers, and Object Initializers. After parsing, JSON objects are realized as ECMAScript objects. JSON arrays are realized as ECMAScript Array instances. JSON strings, numbers, booleans, and null are realized as ECMAScript Strings, Numbers, Booleans, and null.
The optional reviver parameter is a function that takes two parameters, key and value. It can filter and transform the results. It is called with each of the key/value pairs produced by the parse, and its return value is used instead of the original value. If it returns what it received, the structure is not modified. If it returns undefined then the property is deleted from the result.
Let jsonString be ? ToString(text). Parse ! StringToCodePoints(jsonString) as a JSON text as specified in ECMA-404. Throw a SyntaxError exception if it is not a valid JSON text as defined in that specification. Let scriptString be the string-concatenation of "(", jsonString, and ");". Let script be ParseText(! StringToCodePoints(scriptString), Script). Assert: script is a Parse Node. Let completion be the result of evaluating script. The extended PropertyDefinitionEvaluation semantics defined in B.3.1 must not be used during the evaluation. Let unfiltered be completion.[[Value]]. Assert: unfiltered is either a String, Number, Boolean, Null, or an Object that is defined by either an ArrayLiteral or an ObjectLiteral. If IsCallable(reviver) is true, then Let root be ! OrdinaryObjectCreate(%Object.prototype%). Let rootName be the empty String. Perform ! CreateDataPropertyOrThrow(root, rootName, unfiltered). Return ? InternalizeJSONProperty(root, rootName, reviver). Else, Return unfiltered.