Wrote a function to test each object in an array for specific key, continuously getting false even when the key is present

I have a React component where I’m trying to conditionally render a checkbox only if any of the items in a data response contain an object key archived and it’s truthy.

I’ve written a function to check each object but I keep getting false no matter what, even when I add an archived key for each object and I’m not sure what I’m doing wrong.

This is my current function and a working Codesandbox sample:

    const hasArchived = (groupItems) => {
      let answer;

      for (let i = 0; i < groupItems.length; i++) {
        groupItems[i].hasOwnProperty("archived")
          ? (answer = true)
          : (answer = false);
      }

      return answer;
    };

And this is an example of the groupItems data set:

[
 [
   {
     name: 'item 1'
     groupName: 'Marvel Characters'
     archived: false
   },
   {
     name: 'item 2'
     groupName: 'Marvel Characters'
     archived: true
   },
   {
     name: 'item 3'
     groupName: 'Marvel Characters'
     archived: false
   }
 ],
 [
   {
     name: 'item 1'
     groupName: 'DC Characters'
     archived: false
   },
   {
     name: 'item 2'
     groupName: 'DC Characters'
     archived: true
   },
   {
     name: 'item 3'
     groupName: 'DC Characters'
     archived: false
   }
 ]
]

Answer

That’s because your array has two levels of depth, also you could use Array.prototype.some for this use case:

const data = [
 [
   {
     name: 'item 1',
     groupName: 'Marvel Characters',
     archived: false
   },
   {
     name: 'item 2',
     groupName: 'Marvel Characters',
     archived: true
   },
   {
     name: 'item 3',
     groupName: 'Marvel Characters',
     archived: false
   }
 ],
 [
   {
     name: 'item 1',
     groupName: 'DC Characters',
     archived: false
   },
   {
     name: 'item 2',
     groupName: 'DC Characters',
     archived: true
   },
   {
     name: 'item 3',
     groupName: 'DC Characters',
     archived: false
   }
 ]
];

const hasArchived = groupItems => groupItems.some(x => x.some(({ archived }) => archived));


console.log(hasArchived(data));