How to take specific values and sets in JSON

Asked

Viewed 56 times

-1

I have the following JSON

{
  "navigator.zoom.in": "Zoom +",
  "navigator.zoom.out": "Zoom -",
  "badge_name_BR263": "GAMES 6!",
  "badge_name_BR264": "4Anos",
  "badge_name_X2046": "Cabana Aconchegante",
  "badge_desc_X2046": "Duis interdum viverra ante at hendrerit!",
  "badge_name_HBC049": "Solstício de Natal",
  "badge_desc_HBC049": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellu tincidunt!",
  "badge_name_RHBT102": "Suspendisse nec",
  "badge_desc_RHBT102": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellu",
  "badge_name_RHBT103": "Especial de Natal",
  "badge_desc_RHBT103": "Ho, ho, ho... Feliz Natal! Duis interdum viverra ante at hendrerit. Integer elementum tortor!",
  "badge_name_X2047": "Suspendisse nec",
  "badge_desc_X2047": "Lorem ipsum dolor sit amet, consectetur adipiscing elit phasellu tincidunt!",
  "navigator.searchcode.title.popular": "Popular",
  "navigator.searchcode.title.chat_chill_discussion": "Conversas",
  "navigator.searchcode.title.games_events": "Jogos"
}

first need to filter only the badge_name and badge_desc, I was able to filter as follows

const str = JSON.stringify(json);
const match = str.match(/"badge_(name|desc)_(\w+)":"(.*?)"/g).reverse();

now I need a way to extract the code after the _ and then join the badges that have the same code, and if n has been separated, for example

//output
Código: X2047
Titulo: Suspendisse nec
Descrição: Lorem ipsum dolor sit amet, consectetur adipiscing elit phasellu tincidunt!
...
Código: BR264
Titulo: 4Anos
Descrição: Sem descrição

I think I’ll have to go through one for of but I don’t know how to get this data, I’m grateful who can help

  • maybe you need to make a map/reduce of this object to form a new object, see the answers of this question that can help you: https://answall.com/questions/493586/howto travel through a-array-objects-somar-propriedades-espec%C3%adficas-e-unify-es

1 answer

1


One possibility is to iterate the object and work only for the properties that begin with badge_ and in an auxiliary object cataloguing the information:

const obj = {
  "navigator.zoom.in": "Zoom +",
  "navigator.zoom.out": "Zoom -",
  "badge_name_BR263": "GAMES 6!",
  "badge_name_BR264": "4Anos",
  "badge_name_X2046": "Cabana Aconchegante",
  "badge_desc_X2046": "Duis interdum viverra ante at hendrerit!",
  "badge_name_HBC049": "Solstício de Natal",
  "badge_desc_HBC049": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellu tincidunt!",
  "badge_name_RHBT102": "Suspendisse nec",
  "badge_desc_RHBT102": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellu",
  "badge_name_RHBT103": "Especial de Natal",
  "badge_desc_RHBT103": "Ho, ho, ho... Feliz Natal! Duis interdum viverra ante at hendrerit. Integer elementum tortor!",
  "badge_name_X2047": "Suspendisse nec",
  "badge_desc_X2047": "Lorem ipsum dolor sit amet, consectetur adipiscing elit phasellu tincidunt!",
  "navigator.searchcode.title.popular": "Popular",
  "navigator.searchcode.title.chat_chill_discussion": "Conversas",
  "navigator.searchcode.title.games_events": "Jogos"
}

const badges = {}                            //Cria o objeto auxiliar.

/**
 * Indexa uma propriedade e seu valor no objeto auxiliar badges.
 * @function
 * @param {string} p - A propriedade "name"|"desc" que será indexada.
 * @param {string} i - O índice cujo o valor será indexado.
 * @param {string} v - O valor a ser indexado.
 */
function addBadge(p, i, v) {
  //Verifica se i já foi cadastrado...
  if (i in badges) {
    badges[i][p] = v;                       //...se i já foi cadastrado seta a propriedade p com valor v.
  } else {
    badges[i] = {[p]: v};                   //...se p não foi cadastrado cria o índice i setado um novo objeto cujo a propriedade p é setada com o valor v.
  }
}

//Para todos os elementos k:v de obj
for (let [k, v] of Object.entries(obj)) {
  //...se k iniciar com badge_ ...
  if (k.startsWith("badge_")){
    let [_, prop, codigo] = k.split("_");    //...quebra k nos _ separando prop(name/desc) do código numérico.
    addBadge(prop, codigo, v);               //...indexa o valor da propriedade. 
  }
}

//Imprime as propriedades catalogadas.
for (let item in badges) {
  console.log(`Código: ${item}`);
  console.log(`Título: ${badges[item]["name"]}`);
  console.log(`Descrição: ${("desc" in badges[item])?badges[item]["desc"]:"Sem descrição"}`);
  console.log("-------------------------------");
}

References:

Object.()
String.prototype.startsWith()
Scattering Syntax
for...
for...in

  • was exactly what I needed, thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.