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.