0

I have the following the object:

items: [
  {
    object_a {
      id: "1",
      value: "somevalue1"
    }
  },
  {
    object_b {
      id: "2"
      value: "somevalue2"
      items:[
        {
          nested_object_a {
            id: "3"
            value: "somevalue3"
          },
          nested_object_b {
            id: "4"
            value: "somevalue4"
          },
        }
      ]
    }
  },
]

I can check if the value key exists in the initial items array:

items.some(item => item.hasOwnProperty("value"));

To see if the value key exists in the nested object_b item array I can do the following:

items[1].object_b.items.some(item => item.hasOwnProperty("value"));

Instead of specifying which number in the array to look in I need to make the final expression dynamic. I'm certain I need to do a find or a filter on the top level items, but I've had no luck with it so far.

1 Answers1

1

I found that using an every function on the items allowed me to return the boolean value I required form the array. The problem this created is any array item that didn't have the object_b key on was returning null and breaking my app. It turns out I needed to use an optional chaining operator to get around this (.?).

Thanks to @ikhvjs for linking that stackedoverflow article.

Working code:

items.every(item => {
  item.object_b?.items.some(item => item.hasOwnProperty("value"));
});