Home > Software design >  jQuery .each function loop through JSON nested objects
jQuery .each function loop through JSON nested objects

Time:08-03

I have been having hard times trying to get to one specific key/value which is nested into JSON objects

This is the API response

   response: {

    estabelecimento: {

      atividades_secundarias: [{
          id: "6209100",
          secao: "J",
          divisao: "62",
          grupo: "62.0",
          classe: "62.09-1",
          subclasse: "6209-1/00",
          descricao: "Suporte",
          contribuinte: false
        },

        {
          id: "7020400",
          secao: "M",
          divisao: "70",
          grupo: "70.2",
          classe: "70.20-4",
          subclasse: "7020-4/00",
          descricao: "Atividades",
          contribuinte: false
        },

        {
          id: "8211300",
          secao: "N",
          divisao: "82",
          grupo: "82.1",
          classe: "82.11-3",
          subclasse: "8211-3/00",
          descricao: "Serviços",
          contribuinte: false
        }
      ]
    }
  }

The GOAL is to return all descricao items from atividades_secundarias object and store them as a string?

In this case: "Suporte / Atividades / Servicos" ... something like this

Following are the things I have tried:

  • Accessing descricao value by key string
$.each(response.estabelecimento.atividades_secundarias,function(index, item) {
     $.each(index, function (key, val) {
         console.log(val["descricao"]);
     });
});
  • Accessing descricao value using this operator
$.each(response.estabelecimento.atividades_secundarias, function(index, item) {
     $.each(index.id, function (key, val) {
         console.log(this.descricao);
     });
});

I believe it's something very subtle I'm missing.

Thanks

CodePudding user response:

Use $.map() to iterate through atividades_secundarias.

Figure I

//    ⬇️ This is the path to "atividades_secundarias"   ⬇️
$.map(data.response.estabelecimento.atividades_secundarias, function(x, i) { 
//                                  "x" will be the current object ↗️

On each iteration, use Object.keys() on each object (call each object x) within the array. You'll get an array of each object's keys.

Figure II

Object.keys(x) /* [ "id", "secao", "divisao", "grupo", "classe", "subclasse", 
"descricao", "contribuinte" ] *///An array of keys from each object

Next find the key descricao in each object with .includes() and return it's value x.descricao OR null if the object doesn't have that particular key.

Figure III

/* [...<<array of keys>>]*/.includes('descricao') /* if "descricao" is
found...*/ ? /* return it's value */ x.descricao /* Otherwise return */
: null

$.map() returns an array so if you want a string simply use .join().

Figure IV

/*...*/ ).join('/') // "Suporte/Atividades/Serviços"

const data = {
  response: {
    estabelecimento: {
      atividades_secundarias: [{
        id: "6209100",
        secao: "J",
        divisao: "62",
        grupo: "62.0",
        classe: "62.09-1",
        subclasse: "6209-1/00",
        descricao: "Suporte",
        contribuinte: false
      }, {
        id: "7020400",
        secao: "M",
        divisao: "70",
        grupo: "70.2",
        classe: "70.20-4",
        subclasse: "7020-4/00",
        descricao: "Atividades",
        contribuinte: false
      }, {
        id: "8211300",
        secao: "N",
        divisao: "82",
        grupo: "82.1",
        classe: "82.11-3",
        subclasse: "8211-3/00",
        descricao: "Serviços",
        contribuinte: false
      }]
    }
  }
};

const descricaos = $.map(data.response.estabelecimento.atividades_secundarias, function(x, i) {
  return Object.keys(x).includes('descricao') ? x.descricao : null;
}).join('/');

console.log(descricaos);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

CodePudding user response:

If you want to create an array of "descricao" values, you can simply do this:

let descricaoItemsArr = [];
$.each(response.estabelecimento.atividades_secundarias, function(index, item) {
  descricaoItemsArr.push(item.descricao);
});

You don't need a second $.each loop.

  • Related