I have a an object jsonRes[0]
containing values which need to be removed based on a condition. The following works to remove null
, missing values and those equal to zero in the stringified object:
function replacer(key, value) { // Filtering out properties if (value === null || value === 0 || value === "") { return undefined; } return value; } JSON.stringify(jsonRes[0], replacer, "\t")
However, when I add a condition using the the includes
method, I receive an error:
function replacer(key, value) { // Filtering out properties if (value === null || value === 0 || value === "" || value.includes("$")) { return undefined; } return value; } Uncaught TypeError: value.includes is not a function
Why is this the case and is there a workaround?
The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.
The includes() method returns true if a string contains a specified string. Otherwise it returns false . The includes() method is case sensitive.
The every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.
JavaScript Array includes() The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found.
You can use String.indexOf()
instead of String.includes
, As it is available in ES6 and not supported in IE at all.
typeof value == "string" && value.indexOf('$') > -1
Also note if value
is not string type it will still raise an error boolean
, Number
doesn't the the method. You can use typeof
to validate whether value
is a string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With