Iterate through an object, with certain keys being duplicated

Currently, I am facing a scenario where the object I'm analyzing is quite messy...

Essentially, within this object... my goal is to locate the pageviews node, but only if it has 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},
              ]
          }
      }
  ];

There are three instances of "pageviews" within the object.

In the code snippet below, I aim to hide a specific DOM element if pageviews includes data in an array.

Despite my efforts, the DOM element does not hide, leading me to question its efficiency.

What is the most effective approach to accessing "pageviews" or executing a command only if the object contains pageviews with data?

    let searchURL    = new URLSearchParams(location.search);

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

        // Iterate through data obj to locate the desired object
        for (let index = 0; index < data.length; index++) {
            const dataNode = data[index];

            // Verify if the looped node contains "cart"
            if (dataNode.hasOwnProperty("cart")) {

                // Confirm presence of "pageview" node
                if (dataNode.cart.hasOwnProperty("pageview")) {

                    let resultsResponse = dataNode.cart.pageview;

                    if (resultsResponse.length >= 1) {

                        // HIDE DOM ELEMENT IF CONDITION IS MET
                        const bigBlockContainer = document.querySelector('.big-container');
                        bigBlockContainer.remove();
                    }
                }
            }
        }
    }

Answer №1

To filter out specific items based on certain criteria, you can utilize the .filter() method in JavaScript. This method takes a function as a parameter and returns a new array containing only the items that meet the specified conditions:

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

If you are only concerned with checking if any items meet the criteria, you can simplify the process as follows:

if (filteredItems.length) {
    //Perform actions such as removing item from DOM
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Displaying exclusively distinct values in the selection box/dropdown menu

My goal is to retrieve data from the SQL server database and populate the corresponding fields on the frontend. While I am able to fetch the data, some fields in the response contain duplicate values in the dropdown menu. Here is an example of how my Compo ...

Unable to successfully import an external HTML file that contains a script tag

I am currently experiencing an issue with my index.html <!doctype html> <html lang="en"> <head> <meta charset="utf-8> <title>MyApp</title> <link rel="import" href="./common.html"> </head> <body> ...

Displaying only one modal at a time with Bootstrap 3

The code snippet below is used to trigger my newsletter modal: $(window).load(function(){ if (sessionStorage.getItem("is_seen") === null) { setTimeout(function(){ $('#newsletter_modal').modal('show&ap ...

Steps for aligning an image and text within an icon next to each other

I'm looking to align a small PNG image next to some text within an icon. How can I achieve this? Currently, they are stacked vertically. Here is the current layout - I want the two elements side by side instead. The structure of the division is unique ...

Using JavaScript's regular expressions to identify a code block that commences with a specified pattern

Currently, I am working on a JavaScript script and I am in need of a Regex pattern to quickly match "JSDocs". The specific pattern that I am trying to match looks like this: # this is block1 /// text /// text /// text /// text # this is block2 /// text // ...

Having issues with utilizing $fetchState in Nuxt 2.12

Recently, I've been exploring the new functionality outlined in the documentation. However, I'm encountering an error that states : Property or method "$fetchState" is not defined on the instance but referenced during render. Despite clearly ...

Toggle the sidebars to slide out and expand the content division using JavaScript

I am looking to achieve a smooth sliding out effect for my sidebars while expanding the width of the middle content div. I want this action to be toggled back to its original state with another click. Here's what I've attempted so far: $(' ...

In JavaScript, the code is designed to recognize and return one specific file type for a group of files that have similar formats (such as 'mp4' or 'm4v' being recognized as 'MOV')

I am working on a populateTable function where I want to merge different file types read from a JSON file into one display type. Specifically, I am trying to combine mp4 and m4v files into MOV format. However, despite not encountering any errors in my code ...

Automating testing with JavaScript and Selenium WebDriver

Can testing be automated using the combination of JavaScript and Selenium? I am not familiar with Java, Python, or C#, but I do have expertise in Front-End development. Has anyone attempted this before? Is it challenging to implement? Are there any recom ...

Function parameter accepting an anonymous value object

While working with prisma nexus and examining the prismaObjectType, I came across something unusual. A simple example of this is as follows: In a basic function, demo(p), the parameter p should be an object. function demo(p) { console.log(p); con ...

When downloading Facebook API data as a JSON Object and importing it into Google Sheets, there is an issue with the Dates values

Objective: To seamlessly import client data from Facebook Graph API into a Google Sheet in order to build an interactive Facebook Ads Dashboard Methods Attempted: Installed a Google Sheet script with an ImportJSON function designed to import JSON feeds ...

How can "this" be properly utilized in jQuery?

I am attempting to retrieve the title attribute of an element from various elements with the same class, each having different attributes. This is my current approach: HTML <div title="title1" class="pager" onclick="location.href='link.aspx& ...

Interview Question: Calculate the product of all elements in an array excluding the element at the current index

I stumbled upon an interesting interview query and I'm intrigued by the potential solutions. Any thoughts on how to tackle it are encouraged. You have an array A[N] with N numbers. Your goal is to create an array Output[N], where Output[i] represents ...

What is the best way to implement collision detection using raycasting?

For my university project, I am looking to implement collision similar to what is shown in this example. However, I am facing an issue where collision is only working on the top of the object. I referred to this for guidance. My goal is to add collision to ...

Disabling iframe javascript timers when iframe is no longer in the user's view

Currently, I am working on a blog post that will showcase various HTML5/Javascript animations through multiple <iframe> sections. These animations utilize methods such as requestAnimationFrame() and/or setInterval(). Due to limitations within the blo ...

Images in the JavaScript menu are not remaining fixed in place

Can someone help me with my website? I'm having trouble with the menu for different pages, it should stay gray for the active page. It was working fine before I switched to Wordpress, but now I'm not sure what the issue is. Could someone take a ...

Tips for transferring a Spring MVC controller variable to JavaScript

I am currently working on retrieving a variable for a JavaScript function from an object that is sent to the view by the controller. The object I am dealing with is called Bpmsn. https://i.sstatic.net/FxlAo.png Through the controller, I have injected th ...

Search for specific parameters in an array and retrieve them

I have been attempting to sift through an array of data retrieved from my API, but unfortunately, the data remains unfiltered. I suspect that it might be due to the way I implemented my method or perhaps my params are not being returned correctly. Below ar ...

How can PHP Ajax be used to determine when a modal should pop up?

Is there a way to automatically display a modal without refreshing the page? Currently, I have a button that submits to home.php and triggers the modal, but it requires a page refresh for the modal to appear. I'm looking for a solution that will eith ...

I must convert this option into a checkbox

I am facing a challenge with this task, where I need to convert a select form into a checkbox form. Although I have managed to change the visuals, the functionality of the checkboxes does not match that of the select form. Below is the original select for ...