Loop through object, where some keys have same name duplicated

Viewed 69

I'm working on a code base, where annoyingly the object I'm traversing through, is a little messy....

Basically, in my object... I intend to find the pageviews node, but only if it contains an array of data...

Here's an example of the data:

  data = [
      {
        event: "click",
        dimension: 123,
        cart:  {
              pageviews:[]
          }
      },
     {
        event: "scroll",
        dimension: 456,
        cart:  {
              pageviews:[]
          }
      },
     {
        event: "onload",
        dimension: 789,
      },
     {
        event: "click",
        dimension: 'xyz',
        cart:  {
              pageviews:[
                    {data: 1},
                    {data: 2},
                    {data: 3},
              ]
          }
      }
  ];

As you can see, the object contains references of "pageviews" three times.

In my code below, I want to hide a DOM element, if pageviews contains an array of data.

However, my DOM element does not hide. So I don't think it's smart enough.

What is the best way to access "pageviews, or run a command, only if the object contains pageviews with data?

    let searchURL    = new URLSearchParams(location.search);

    if (searchURL.has("a" && "b" && "c")) 

        // Loop through data obj to find which object
        for (let index = 0; index < data.length; index++) {
            const dataNode = data[index];

            // Check if loop contains node contains "cart"
            if (dataNode.hasOwnProperty("cart")) {

                // Check if "pageview" node exists
                if (dataNode.cart.hasOwnProperty("pageview")) {

                    let resultsResponse = dataNode.cart.pageview;

                    if (resultsResponse.length >= 1) {

                        // THEN HIDE DOM ELEMENT
                        const bigBlockContainer = document.querySelector('.big-container');
                        bigBlockContainer.remove();
                    }
                }
            }
        }
    }
1 Answers

You can use the .filter() function, which takes a function as parameter and generates a new array which contains only the items that fulfill the criteria you passed:

var interestingSubset = data.filter((item) => item.cart && item.cart.pageviews && item.cart.pageviews.length);

Now, if you are only interested to see whether there is at least an item that fulfills your criteria, then you can do this:

if (interestingSubset.length) {
    //Remove item from DOM or do whatever you need to do
}
Related