Having trouble grouping data on website due to duplicate names

Currently in the process of scraping data from various websites and looping through it. Specifically focusing on scraping the head section.

This is an example illustrating the structure of the data:

const head = {
    rel_data: [
      {
        rel: "rel",
        items: [
          {
            type: "type",
            sizes: "sizes",
            href: "href"
          }
        ]
      }
    ]
};

The goal is to insert data into items whenever a match is found for the rel.

$('head link').each(function(index) {
if(head?.rel_data[index]?.rel == rel) {
  head?.rel_data[index]?.items.push({
    type: (type !== undefined) ? type : null,
    sizes: (sizes !== undefined) ? sizes : null,
    href: (href !== undefined) ? href : null
  });
} else {
  head.rel_data.push({
    rel: (rel !== undefined) ? rel : null,
    items: [
      {
        type: (type !== undefined) ? type : null,
        sizes: (sizes !== undefined) ? sizes : null,
        href: (href !== undefined) ? href : null
      }
    ]
  });
}
})

Here is what is expected:

rel_data: [
  {
    rel: "icon",
    items: [
      {
        type: "type",
        sizes: "sizes",
        href: "href"
      },
      {
        type: "type",
        sizes: "sizes",
        href: "href"
      }
    ]
  },
  {
    rel: "other-rel-type",
    items: [...]
  }
]

However, the result obtained is not as expected:

rel_data: [
  {
    rel: "icon",
      items: [
        {
          type: "type",
          sizes: "sizes",
          href: "href"
              }
    ]
  },
  {
    rel: "icon",
      items: [
        {
          type: "type",
          sizes: "sizes",
          href: "href"
      }
    ]
  }
]

When replacing index with 0, it functions correctly for the initial type of rel (such as icon) but not for others?

Answer №1

To optimize the data storage process, consider utilizing a temporary object instead of an array and utilize the rel values as keys.

Upon completion, you can retrieve the final array by using Object.values(tempObject)

An example structure of this object would resemble:

const tempObj = {
  "icon": {
    rel: "icon",
    items: [{
        type: "type",
        sizes: "sizes",
        href: "href"
      }

    ]
  },

  "other-rel-type": {
    rel: "other-rel-type",
    items: []
  }
}

A refined version of the loop procedure could be as follows:

$('head link').each(function(index) {
    const rel = this.rel
    tempObj[rel] = tempObj[rel] || { rel, items:[]}

    tempObj[rel].items.push({type:..., sizes:...})

});

Lastly,

head.rel_data = Object.values(tempObj)

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

Examine the syntax of JavaScript

I've been digging into a piece of code written by another person. My focus is on uncovering the JavaScript function that executes when the link below is clicked.... <a href="#subtabs_and_searchbar" id="finish_counting" onclick="$(' ...

"Automating form filling in JavaScript with Python: A step-by-step guide

I am looking to automate filling out this particular form using Python. I have attempted to use Mechanize, but since this Microsoft Form utilizes JavaScript and does not have any form tag or GET/POST URL, I am facing challenges. Perhaps BeautifulSoup/Sele ...

Simplify your bootstrap Input field code by utilizing components or a similar method in Vue.js

Using a single file component with a pug template, I am faced with multiple input fields that have the same formatting. Here is an example: .input-group.input-group-sm .input-group-addon Purchase Price input.form-control(v-model='purchase_ ...

The response from unirest in node.js came back as undefined

Currently, I am diving into the world of Facebook bots, despite not being well-versed in node.js development. Stepping out of my comfort zone and embracing this new challenge for the first time has been quite exhilarating. Below is the function that I hav ...

Unending React cycles - invoking setState() within a render onClick

Recently delving into React and facing an issue with rendering a button component. My goal is to create a button that, upon being clicked, fetches data and displays it as a list below the button. To achieve this, I am attempting conditional rendering. I ut ...

Cross-origin resource sharing problem arises when JavaScript is loaded asynchronously using script tags created dynamically

By dynamically creating a script as shown below, the JavaScript source is downloaded asynchronously. let newScript = document.createElement('script'); newScript.src = srcUrl; let firstScript = document.getElementsByTagName('script')[0] ...

What is the most effective way to loop and render elements within JSX?

Trying to achieve this functionality: import React from 'react'; export default class HelloWorld extends React.Component { public render(): JSX.Element { let elements = {"0": "aaaaa"}; return ( ...

If the width of the window is below 768px, do not execute the function

In order to prevent the showCover() function from firing when the window width is less than 768px on page load AND resize, I have made some adjustments to the code below. Even though the window is smaller than 768px, the function will not be triggered. ...

Custom control unable to display MP3 file

Hey, I came across this awesome button that I am really interested in using: https://css-tricks.com/making-pure-css-playpause-button/ I'm currently facing two issues with it. First, I can't seem to play the sound. I've placed the mp3 file ...

Creating a PHP array filled with fresh objects

As I work on developing a web-based administration frontend for my PHP application (after encountering issues with Lua and Nginx), I am facing frustration with PHP's arrays. In an attempt to initialize an array of objects, similar to what I would do ...

Attaching a modal to an entity

I am currently working on binding a Knockout (KO) viewmodel to a Bootstrap modal, but it seems like I am overlooking a step to direct KO to fill in the input fields. Below is the current setup: The template for the modal: <script type="text/html" id= ...

Guidelines for passing a value to a method within a method using JavaScript

I am currently exploring how jQuery can be used to select an element, retrieve an attribute, and assign it a new value. While I have successfully managed to select the element and extract the attribute, I am facing difficulty in setting the attribute using ...

As the height is expanded, the background color gradually infiltrates the body of the page

I am currently working on an angular application that utilizes angular-pdf. The controller and view function perfectly, and the PDF is displayed correctly, except for one issue. The height of the PDF exceeds the min-height of the module, causing it to expa ...

Sending AJAX data from VIEW to CONTROLLER in PHP (MVC) using AJAX: A step-by-step guide

I have a page at http://visiting/blog. The Controller contains two methods: action_index and add_index. When Action_index() executes, it returns pages with indexes. On the other hand, Add_index() invokes a model's method called add_data(), which inse ...

Tips for effectively loading data of a specific user or event into a bootstrap modal in Laravel using AJAX

I'm having some trouble loading Event data into my bootstrap modal in Laravel. This is all new to me as I'm just getting started with AJAX. Can someone please take a look at what I've done so far? Modal Template <div class="modal fa ...

Can the Angular.js scope be maintained while also making changes to the template?

I am currently facing a challenge with my directive. In the snippet below, I am attempting to extract content from a template, append it to the layout, and then compile it: var $template = angular.element("<div></div>"); $template.append($co ...

Adding Numerous Elements to a Container

In my HTML code, there is a div element with the id of controls. I am attempting to add a div containing 2 input fields using this method: this.controls = controlBtns .append('div') .classed({'time-container': true}) .appe ...

What is the best way to incorporate an exported TypeScript class into my JavaScript file?

One of my JavaScript files is responsible for uploading a file to Microsoft Dynamics CRM. This particular JavaScript file makes use of RequireJS to reference another JavaScript file. The referenced JavaScript file, in turn, was compiled from multiple Typ ...

Integrate your React Native application with a Node.js backend on your local machine

My attempt to establish a connection between my react native app and my node.js app on a Windows system has hit a roadblock. While I am able to receive responses from the node API using Postman, the response from the react native app is coming back as unde ...

Issue with datetime picker in JavaScript/jQuery: Input fields added dynamically are not showing the datetime picker

I am currently investigating why the datetime picker does not work on a dynamically added input block within a table cell. A code snippet below serves as a proof of concept for this issue. In its present state, the default input tag (id: dti1) functions co ...