Skip to content
Advertisement

every() es6 for nested array is not working?

I expect true for below usage of every but it wasn’t, what’s wrong with my logic?

const isAllChecked = [
    {
        "id": "1",
        "checked": true,
    },
    {
        "id": "2",
        "checked": true,
        "nested": [
            {
                "id": "2.1",
                "checked": true,
            },
            {
                "id": "2.2",
                "checked": true,
            }
        ]
    },
    {
        "id": "3",
        "checked": true,
    },
].every(
    (o) =>
      o.checked &&
      o.nested?.every((o) => o.checked)
  )

What I wanted: if any of the level 1 checked or nested checked is false then isAllChecked is false, but if non of the checked property in level 1 or nested is false, isAllChecked should return true.

Advertisement

Answer

Optional chaining will evaluate to undefined if the chain fails, so for the second iteration

(o) =>
  o.checked &&
  o.nested?.every((o) => o.checked)

will evaluate to

(o) =>
  true
  undefined

You probably wanted

(o) =>
  o.checked &&
  (!o.nested || o.nested.every((o) => o.checked))

or

(o) =>
  o.checked &&
  (o.nested || []).every(o => o.checked)

const isAllChecked = [
    {
        "id": "1",
        "checked": true,
    },
    {
        "id": "2",
        "checked": true,
        "nested": [
            {
                "id": "2.1",
                "checked": true,
            },
            {
                "id": "2.2",
                "checked": true,
            }
        ]
    },
    {
        "id": "3",
        "checked": true,
    },
].every(
    (o) =>
      o.checked &&
      (o.nested || []).every((o) => o.checked)
  )
console.log(isAllChecked);
Advertisement