Home > Software design >  Includes method doesnt return true for key extracted from Object.entries of Array
Includes method doesnt return true for key extracted from Object.entries of Array

Time:02-22

I am trying to filter objects who key's correspond to values in an array of arrays. So 3 sets of objects each filtered by their placement in an array. (Objects are listed in an array.) I suspect this is a two-part question. Why doesn't the Array.prototype.includes method return true, when the case is true?

boardObj =  [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]

const winCol = (boardObj) => {
        const indexes = [[0,1,2], [3,4,5], [6,7,8]];
        let result = indexes.filter((ele) => {
            for (const [k, v] of Object.entries(boardObj)) {
                console.log(ele.includes(0))
                console.log(ele.includes(k))
                if (ele.includes(k)) {
                     return v
                }
            }
            
        })
        console.log(result)
    }

CodePudding user response:

Property names are always string values:

console.log(typeof Object.keys({0: 42})[0]);

But Array#includes basically performs strict comparison, so string values will never be equal to number values.

You can convert your indexes array to an array of arrays of string values, or convert the property name to a number value.

console.log(
  [0,1,2].includes(Number(Object.keys({0: 42})[0]))
);
console.log(
  ['0','1','2'].includes(Object.keys({0: 42})[0])
);

You could also use Array#some and perform "loose" comparison instead:

const key = Object.keys({0: 42})[0];
console.log([0,1,2].some(e => e == key));

  • Related