.includes() question

Discuss how to use and promote Web standards with the Mozilla Gecko engine.
Post Reply
Bethrezen
Posts: 445
Joined: September 13th, 2003, 11:56 am

.includes() question

Post by Bethrezen »

Hi all

When working with JavaScript objects is there a way to check if partial keys exist so for example say I have an object like this

Code: Select all

var object = 
{
  name1: "john",
  name2: "jack",
  name3: "bill", 
};
Rather then doing

Code: Select all

if ("name1" in object) {//do something}
if ("name2" in object) {//do something}
if ("name3" in object) {//do something}
Is there a way I could do a partial key match for example

Code: Select all

if ("name" in object) {//do something}
I would of assumed that there would be a simple way to do this something like

Code: Select all

if (Object.keys(object).includes("name")) {//do something}
However for some reason this is returning false when it should be returning true and I don’t understand why because Object.keys(object) returns an array of strings in this case

Code: Select all

Array ["name1", "name2", "name3"];
Therefore Object.keys(object).includes("name") should return true, as the returned array does indeed contain the partial string "name"

As far as I can tell .includes("name") should search a string for the specified value so for example

Code: Select all

var string = "name1 name2 name3";

console.log(string.includes("name"));
returns true as the string does indeed contain "name" so why is it that when working on a string .includes() works as expected and returns true but when applying this to an array of strings it will only return true on an exact match

when I would of assumed that it would search each value in the array for the specified string in this case "name" and return true since all 3 values do contain the partial string "name"
b4ckerCrazyMit
Posts: 39
Joined: July 10th, 2022, 3:43 am
Location: Moz Office, SF, USA
Contact:

Re: .includes() question

Post by b4ckerCrazyMit »

The value should be precise like indexOf, it's not like SQL using LIKE, it's more like, you must use the full text content, not only partial text you want to search with. Probably better to have forEach to check whole content, because includes in array mean exact value.

See more in https://developer.mozilla.org/en-US/doc ... y/includes

There are workarround tho, you can implement Array.prototype.valContain() like this

Code: Select all

Array.prototype.valContain = function(e) {
//console.log(arguments)
for (var i = 0; i < this.length; i++)
{
if (this[i].includes(e)) return true;
}
return false;
}
then you can test it using

Code: Select all

var object = 
{
  name1: "john",
  name2: "jack",
  name3: "bill", 
};

console.log(Object.keys(object).valContain("name"));
It should return true, because includes on array proto also iterate using forEach() as I know.
Post Reply