Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

157
Visualizações
Checking for duplicate property values in an array of nested objects

I have a JSON file with an array that has nested objects and arrays that simulates a shopping cart. I want to check for duplicate values and if there are any, update the quantity value of the item otherwise, just add the items to the cart.

Here is the JSON file:

[
    {
        "email": "tshepo@email.com",
        "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
            }
        ]
    }
]

And here is what I have done 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);
    }
}

The code does not work the way it's supposed to, please help.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

There were quite a few errors in your code, I have fixed them. What seemed to confuse you the most was that you had an array of a single item, that is an object, which has an items member that's an array as well. So, we needed to refer data[0].items[x] instead of data[x]. Also, in your checkIfPresent function you checked whether data contains the item, which is obviously true. Always. Instead, you wanted to check whether an item of the same name was already processed, so you needed to check whether arr already had this value. Finally, arr is initialized in every iteration of your loop, which removes anything that was stored in an earlier iteration and makes it unaccessible outside the loop. I moved the initialization outside the loop. Also, since your data has an array, it seems that you may have several shoppings. In which case you can wrap another loop around the loop that you already have and loop data's main index as well.

let data = [
    {
        "email": "tshepo@email.com",
        "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);

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda