Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using .includes method in a function

Tags:

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?

like image 601
the_darkside Avatar asked Jan 24 '17 05:01

the_darkside


People also ask

What does .includes do in JavaScript?

The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.

How do I check if a string contains a specific word in JavaScript?

The includes() method returns true if a string contains a specified string. Otherwise it returns false . The includes() method is case sensitive.

What does the every () method do?

The every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.

How do you check if JavaScript array contains a 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.


1 Answers

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.

like image 82
Satpal Avatar answered Sep 18 '22 21:09

Satpal