Analyzing the components within an object

Currently, I am developing a web scraper that stores results in a JSON format similar to the following:

{"Products" : [
   {"Title":"Voice Recorder ISD1932","Results": [
      {"Stock":1,"Price":11.4,"Date":"18-8-2014:3:36"},
      {"Stock":1,"Price":12.4,"Date":"18-8-2014:3:38"},
      {"Stock":1,"Price":12.4,"Date":"19-8-2014:0:40"},
      {"Stock":1,"Price":12.4,"Date":"19-8-2014:21:46"},
      {"Stock":1,"Price":12.4,"Date":"21-8-2014:22:4"},
      {"Stock":1,"Price":12.4,"Date":"22-8-2014:0:40"},
      {"Stock":1,"Price":12.4,"Date":"23-8-2014:0:48"},
      {"Stock":1,"Price":12.4,"Date":"23-8-2014:13:56"},
      {"Stock":1,"Price":12.4,"Date":"23-8-2014:13:56"},
      {"Stock":1,"Price":12.4,"Date":"23-8-2014:13:56"},
      {"Stock":1,"Price":12.4,"Date":"23-8-2014:13:56"}, 
      {"Stock":1,"Price":12.4,"Date":"23-8-2014:13:56"},
      {"Stock":1,"Price":12.4,"Date":"23-8-2014:13:56"}],
    "id":"4a1e90d7-e578-4bd5-b888-38c7bbfb4af5"}]}

For example, the first element in the results would be:

{"Stock":1,"Price":11.4,"Date":"18-8-2014:3:36"}

The second would be:

{"Stock":1,"Price":12.4,"Date":"18-8-2014:3:38"}

And so on.

Each time I scrape the website, it adds a new element.

I am looking to implement a cleaner function that removes an element if both stock and price are equal to the previous one, excluding the date information.

Using this example, if the third element is identical to the second, I want to remove it. The same goes for subsequent elements.

Answer №1

If you want to achieve this task effortlessly, utilize the array.filter method:

let data = ...;

for(let i = 0 ; i < data.Products.length ; i++) {
    let product = data.Products[i];
    product.Items = product.Items.filter(function(item, index, array) {
        return index == 0 || !(item.Quantity === array[index - 1].Quantity && item.Price === array[index - 1].Price);
    });
}

Answer №2

VIEW DEMO

Here's a method to iterate through objects and remove duplicates based on a specified criterion:

var arr = {"Products" : [
   {"Title":"Voice Recorder ISD1932","Results": [
      {"Stock":1,"Price":11.4,"Date":"18-8-2014:3:36"},
      {"Stock":1,"Price":12.4,"Date":"18-8-2014:3:38"},
      {"Stock":1,"Price":12.4,"Date":"19-8-2014:0:40"},
      {"Stock":1,"Price":12.4,"Date":"19-8-2014:21:46"},
      {"Stock":1,"Price":12.4,"Date":"21-8-2014:22:4"},
      {"Stock":1,"Price":12.4,"Date":"22-8-2014:0:40"},
      {"Stock":1,"Price":12.4,"Date":"23-8-2014:0:48"},
      {"Stock":1,"Price":12.4,"Date":"23-8-2014:13:56"}, 
      {"Stock":1,"Price":12.4,"Date":"23-8-2014:13:56"}
    ],
    "id":"4a1e90d7-e578-4bd5-b888-38c7bbfb4af5"}]};

var data = arr.Products[0].Results;

for(var i = 0; i != data.length; i++) {
    var stock = data[i].Stock;
    var price = data[i].Price;
    var date = data[i].Date;
    if( i < data.length - 1 && date === data[i + 1].Date) {
        data.splice(i + 1,1);
        i--;
    }
}

Answer №3

Here is the code snippet in JavaScript:

var data = { "output": {} };
var outputData = {};
var temporaryArray = [];
for(var i = 0; i < 10; i++){
    var stockValue = i + 20;
    var priceValue = "14." + (i + 10);
    var fetchValue = '12' + i;
    outputData = {'stock': stockValue, 'price': priceValue, 'fetch': fetchValue};
    if(i == 0) {
        temporaryArray.push(outputData);
    } else {
        var lastObject = temporaryArray[temporaryArray.length - 1];
        if(lastObject.stock == stockValue && lastObject.price == priceValue){
            console.log("Match found"); // If a match is found, do not add
        } else {
            temporaryArray.push(outputData);
        }
    }
}
data.output = temporaryArray;
JSON.stringify(data);

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

Issues with border/padding and overlay in Packery Grid Layout

After spending some time working on a grid layout using the metafizzy isotope packery mode, I have encountered a few issues. To illustrate my problem, I have provided a link to a codepen below: http://codepen.io/anon/pen/EgKdpL Although I am satisfied wi ...

Lack of defined global array in JavaScript

I'm encountering an issue with this JavaScript code. The second alert in the (tracking_data) is displaying 'undefined', as if the variable had been deleted or cleared, but I cannot find any part of the code that would cause that. Any assista ...

Column alignment issue detected

Can you help me with aligning the data in my column status properly? Whenever I update the data, it doesn't align correctly as shown in the first image. https://i.stack.imgur.com/300Qt.png https://i.stack.imgur.com/4Dcyw.png $('#btn_edit' ...

Creating an interactive chart with Rickshaw that updates dynamically without the need to refresh the browser

My goal is to create a dynamic graph that continuously updates with fresh data without having to refresh the entire page. The example I found uses random data to build the graph, but the issue is that the data is not always up-to-date unless I manually ref ...

Issue with this.setState() not updating value despite not being related to asynchronous updates

Just a quick note, this specific question does not involve any asynchronous update problem (at least, as far as I can tell). I currently have a class component with the following code snippet (simplified for clarity on the main issue): constructor(props ...

Massive HTML Table Containing Rows upon Rows

Currently, I have a server that can provide me with a list of objects in json format, and my goal is to showcase them in a table on the client side. Initially, I thought about dynamically modifying the DOM after receiving data from the server. Building th ...

Implementing child components rendering in a React application using TypeScript

Just a little background information: I am attempting to build a carousel with pagination using ReactJS. Here is the code snippet I currently have: interface HTMLCarouselT { children: Array<JSX.Element> size: number; } const HTMLCarousel = ({ch ...

Can JavaScript functions be automated on a web browser using Power BI tables?

I am facing a challenge with saving data from a powerbi table on a daily basis. When I hover over the table and click on the ellipsis menu, a button element is generated in HTML that allows me to save the data to a CSV file using Selenium. However, achiev ...

The Jenkins build on a specific branch is encountering issues with path exporting, causing it to fail

I have a set of files related to a new feature that I am trying to deploy through Jenkins. I have successfully deployed other branches in the past, but I am encountering difficulties with a specific branch. https://i.sstatic.net/BKVbH.png I believe the pro ...

Discover the best way to connect your Chrome bookmarks to a server through an extension using an API

I have embarked on creating a unique Chrome extension that will enable users to not only view, update, create, and delete Chrome bookmarks but also save and retrieve bookmarks through our server without the need for Google account synchronization. One chal ...

Submitting an Ajax form refreshes the page

After submitting the form, the page reloads and I am trying to prevent that from happening. Latest Update: After receiving some feedback, I have made changes to my code. The form submission now works correctly, but the page still reloads. Previously, this ...

Retrieve a different action instance variable within the view

In the scenario where I have a View called home.html.erb and the corresponding controller shown below: class StaticController < ApplicationController def home @people = Person.all end def filter @people = .... end def contact end ...

Ways to retrieve information and functions from defineExpose in Vue

`I am attempting to call a method from a child component within the parent component in Vue using the composition API. I have defined the method inside defineExpose, but I am unable to access it in the parent component. Hero.vue (ChildComponent) <templ ...

The JQuery AJAX Done function fails to execute

$('#loginForm').submit(function(e){ var $inputs = $(this).find("input"); var serializedData = $(this).serialize(); $inputs.prop("disabled", true); var request = $.ajax({ url: "myurl", d ...

Triggering multiple functions by clicking on the Icon

I'm trying to execute two different functions when the user clicks on the Icon, but I keep getting an error that says: Expected onClick listener to be a function, instead got a value of object type. Can someone please help me figure out what I am doin ...

Confirming if a JSON is valid in the C programming language

After hours of searching on Google, I am eager to find a way to programmatically verify if the string provided below is valid JSON using C. Is there any solution available? (I am currently relying on the json-c library.) char * jsonString = "{ ...

Tips on incorporating the authorization header in the $.post() method with Javascript

When attempting to POST data to the server, I need to include an Authorization header. I attempted to achieve this using: $.ajax({ url : <ServiceURL>, data : JSON.stringify(JSonData), type : 'POST', contentType : "text/html", ...

Having issues retrieving a JSON array in PHP with the json_decode function

Can someone assist me with passing and returning an array to a PHP script? I have successfully tested the json_encode portion, but I am facing issues with the json_decode on the PHP side. Javascript scid_list = []; $('.filter_on').each ...

Is it possible for the ".filter" function to verify if the target contains multiple attributes?

I'm currently working on a checkbox filter setup and using Jquery's .filter to sort through some divs. Below is the snippet of Jquery code that I am using: $(document).ready(function(){ var checkboxes = $('div.filter-groups').find(&ap ...

having difficulty accessing the value within the Angular constructor

My current issue arises when I click on a button and set a value within the button click method. Despite declaring the variable in the constructor, I am unable to retrieve that value. The code snippet below demonstrates this problem as I keep getting &apos ...