Detecting repeated property values within a collection of embedded objects

I am currently working with a JSON file that contains an array of nested objects and arrays to represent a shopping cart. My goal is to identify duplicate values and update the quantity of the item if duplicates exist, otherwise simply add the items to the cart.

Below is the content of the JSON file:

[
    {
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="93e7e0fbf6e3fcd3f6fef2faffbdf0fcfe">[email protected]</a>",
        "status": "OPEN",
        "items": [
            {
                "name": "hamster",
                "quantity": 2,
                "price": 20
            },
            {
                "name": "saw dust",
                "quantity": 1,
                "price": 20
            },
            {
                "name": "hamster-cage",
                "quantity": 1,
                "price": 150
            },
            {
                "name": "book: how to care for your hamster",
                "quantity": 1,
                "price": 150
            },
            {
                "name": "hamster-cage",
                "quantity": 1,
                "price": 150
            }
        ]
    }
]

Here is an overview of what I have implemented so far:

const data = require("./data.json");

function checkIfPresent(key){
    let ans = data.findIndex((obj) => Object.values(obj).includes(key))
    return ans;
}

for(let x = 0; x < data.length; x++)
{
    let arr;
    if(checkIfPresent(data[x].items)){
        arr[ans].quantity += data[x].items.quantity;
    }else{
        arr.push(data[x].items);
    }
}

I am facing issues with the functionality of the code and would appreciate any assistance to resolve it.

Answer №1

After reviewing your code, I noticed several errors that needed to be addressed. One key issue was the handling of an array containing a single object with an "items" member that is also an array. This required referencing the items using data[0].items[x] instead of data[x]. Additionally, the checkIfPresent function was incorrectly checking for the presence of the entire object in the array instead of checking for a specific value. It was critical to check if the item name was already processed by examining the arr array. Moreover, the loop initialization was resetting the array in each iteration, preventing access to previous data. To solve this, I moved the initialization outside the loop. Furthermore, since the data array contained multiple shopping instances, it was necessary to wrap another loop around the existing one to iterate over the main index of data.

let data = [
    {
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bbcfc8d3decbd4fbded6dad2d795d8d4d6">[email protected]</a>",
        "status": "OPEN",
        "items": [
            {
                "name": "hamster",
                "quantity": 2,
                "price": 20
            },
            {
                "name": "saw dust",
                "quantity": 1,
                "price": 20
            },
            {
                "name": "hamster-cage",
                "quantity": 1,
                "price": 150
            },
            {
                "name": "book: how to care for your hamster",
                "quantity": 1,
                "price": 150
            },
            {
                "name": "hamster-cage",
                "quantity": 1,
                "price": 150
            }
        ]
    }
]
function checkIfPresent(key, array){
    let ans = array.findIndex((obj) => obj.name === key)
    return ans;
}

let arr = [];var ans;
for(let x = 0; x < data[0].items.length; x++)
{
    if((ans = checkIfPresent(data[0].items[x].name, arr)) >= 0){
        arr[ans].quantity += data[0].items[x].quantity;
    }else{
        arr.push(data[0].items[x]);
    }
}
console.log(arr);

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

Tips for sorting through the state hook array and managing the addition and removal of data within it

Having trouble finding a solution for filtering an array using the React useState hook? Let me assist you. I have declared a string array in useState- const [filterBrand, setFilterBrand] = useState<string[]>([]); Below is my function to filter this ...

Unable to display JSON object on the screen

My current code is a snippet from my Asynctask that retrieves JSON data from a URL, parses it, and displays the information in TextViews on the screen. I suspect that the problem lies within the onPostExecute section where I am trying to pass the JSON info ...

Is there a method to update the res object following a couchbase DB call without encountering the error "Error: Can't set headers after they are sent"?

let express = require('express'); let searchRoute = express.Router(); searchRoute.get('/', function(req, res, next) { console.log('1'); databaseCall(function(error, result) { if (error) { res.sta ...

The optimal method for storing tokens in Vue when using Laravel Sanctum

I am currently working on an application built with Laravel and Vue.js. My current focus is implementing the login/logout functionality using Laravel Sanctum. Here is my scenario: I already have the backend methods for login/logout/register set up, but I ...

Having issues with the jQuery toggle functionality

var resultsList = $("#test"); resultsList.text("Hello. This is jQuery!"); var tB = jQuery("#toggleButton"); tB.on("click", function() { resultsList.toggle(400); }); The syntax appears to be correct as there are no errors reported in the browser cons ...

Navigating through an ajax-based webpage entirely with selenium webdriver

I have attempted to scroll a page entirely using the following code: var scrollToBottom = function() { window.scrollTo(0, Math.max(document.documentElement.scrollHeight, document.body.scrollHeight, document.documentElement.clientHeight)); }; window.on ...

Is there an issue with .addClass not working on imported HTML from .load in jQuery?

I have set up a navigation bar that hides when the user scrolls down and reappears when they scroll up. I want to keep the navbar code in a separate HTML file for easier editing. .load In the index.html file, the navbar code is included like this: <di ...

The transparency level of materials in THREE.js

When using the lambert shader, I encountered an issue with setting the material. In the example provided, it sets the material as follows: this.material.uniforms.emissive.value = new THREE.Color( Math.random(), Math.random(), Math.random()); Prior ...

When attempting to import and utilize a component from a personalized React Component Library, it leads to an Invariant Violation error stating: "

Currently, I am in the process of developing a React UI Kit/Component Library for internal use in our product line. Progress has been smooth so far, with everything functioning well and displaying correctly on Storybook. However, when testing the library ...

The mysterious unknown variable dynamically imported: ../views/Admin/Home.vue in Vue3-vue-router4 has sparked curiosity

When utilizing Vue3, Vuerouter4, and Vite I am attempting to import components and routes into the vue router, but I am encountering an error (only for the route that contains children in my paths): https://i.sstatic.net/TFGvr.png This is my router code ...

Using JavaScript to extract the metadata of an image from a remote location

Is there a way to extract XMP metadata from a JPEG file using JavaScript? I came across a method for doing it in PHP (How can I read XMP data from a JPG with PHP?) which can be adapted for JavaScript using AJAX. However, the issue arises when trying to acc ...

Ways to perform a redirect following data retrieval from a post request

I am working on a post method for a servlet, where the servlet returns a web page after forwarding a request to another page. Instead of directly redirecting using window.location = "/AnotherServlet", I have tried various solutions including passing parame ...

Need assistance using a form within a popover in Angular UI Bootstrap?

I have implemented a button that triggers an Angular UI Bootstrap popover by using a template. If you want to see it in action, you can check out this demo The popover template consists of a form containing a table with various text fields that are bound ...

Tips for creating a responsive carousel slider for images

No matter how much I've tried, I can't seem to find a solution on how to make my image responsive along with the caption. Below is my HTML code: <section id="banner"> <div class="banner-bg"> <div class="banner-bg-item ...

What is the proper way for AJAX to function in WordPress when there is no output function available?

I am looking to incorporate AJAX functionality into my WordPress site to make a call to a third-party API. The goal is to update the state of some checkboxes based on the response received. While I have experience with AJAX, my previous implementations in ...

Extremely sluggish pagination in JQGrid following the implementation of a filter through the filter toolbar

I've encountered a problem while using jqGrid with LOAD ONCE and client-side paging. The addition of a filter toolbar has significantly slowed down the paging process after applying any kind of filter. $(gridElement).jqGrid({ postData: post, ...

Distinguishing each unique JavaScript property within an array of objects

I've been struggling with this problem for quite some time. I have an array of objects, focusing on the "00" object at the moment, and I am trying to group together the bestScore properties in a specific way: .. User Group apple .. User Group ba ...

Is it possible to sketch basic 2D shapes onto 3D models?

Is the technique called projective texture mapping? Are there any existing library methods that can be used to project basic 2D shapes, such as lines, onto a texture? I found an example in threejs that seems similar to what I'm looking for. I attempt ...

JavaScript: table is not defined

When creating a table using Django models and JavaScript, I encountered an issue where the cells values of the table could not be accessed from another JavaScript function. The error message indicated that the table was "undefined". Below is the HTML code ...

Node is currently posing a challenge for the installation of packages

I am currently facing an issue while setting up my raspberry pi 3. I am attempting to install and execute a node code, but I encountered a problem during the installation of packages using npm. After trying multiple times with different versions of node ( ...