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

166
Visualizações
Remove object that have an empty array value

So I have an object inside a json file like this:

{
    "0": {
        "damage_type": "Scratch",
        "regions": []
    },
    "1": {
        "damage_type": "Dent",
        "regions": []
    },
    "2": {
        "damage_type": "Dent",
        "regions": [
            "front side",
            "front window"
        ]
    }
}

What I am trying to accomplish is to remove the object that have empty regions. Like this:

{
    "2": {
        "damage_type": "Dent",
        "regions": [
            "front side",
            "front window"
        ]
    }
}

I am using a for loop and still unsuccessful:

jsonfile.readFile(theJsonFile, function (err, obj) {
    if (err) console.error(err)

    for (var i = 0; i <= Object.keys(obj).length - 1; i++) {
      if (obj[i].damage_type.length < 1) {
        delete obj[i]
      } 
    }
}

Any ideas?

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

0

Calling the parsed value damages instead of obj, you can grab all entries as key/value pairs, iterate over them and remove no-region "damages" by their ids:

Object.entries(damages).forEach(([id, damage]) => {
  if (!damage.regions.length) {
    delete damages[id];
  }
});

Alternatively, you can create a brand new structure without touching the original structure:

const entries = Object.entries(damages);
const filteredEntries = entries.filter(([_, damage]) => damage.regions.length);
const filteredDamages = Object.fromEntries(filteredEntries);
about 4 years ago · Juan Pablo Isaza Relatório

0

In this case first you need an array. To convert object to arrays use entry entry

let obj = {
    "0": {
        "damage_type": "Scratch",
        "regions": []
    },
    "1": {
        "damage_type": "Dent",
        "regions": []
    },
    "2": {
        "damage_type": "Dent",
        "regions": [
            "front side",
            "front window"
        ]
    }
}

converting array :

const myentry= Object.entries(obj);

Now the best way to eliminate or filter array is to use filter method and in return get the other object which have filter value.

Filter

const myFiletrObj = myentry.filter(([_, obj]) => obj.regions.length).reduce(withObjectAssign, {})

function withObjectAssign(object, [key, value]) {
  return Object.assign(object, {[key]: value})
}

This will give you filtered output.

about 4 years ago · Juan Pablo Isaza Relatório

0

You can delete a json node by its key

var json = { ... };
var key = "foo";
delete json[key]; // Removes json.foo from the dictionary.
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