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

86
Visualizações
print out object array based on level

I want to print out a list formatted by level. What I have is an array of objects.

Each object has a level eg 0, 1, 2. 0 being the uppermost and 2 being the innermost level. I want to print out the list with a indentation to each inner level

So a list would look like this

0
    1
    1
         2
         2

What my code looks like:

for (let category of json.categories) {
  if ((category.level = 0)) {
    console.log(
      category.category + "https://www.example.com/" + category.seo_name
    );
  }

  else if ((category.level = 1)) {
    console.log(
      "   " +
        category.category +
        " " +
        "https://www.example.com/" +
        category.seo_name
    );
  }

 else if ((category.level = 2)) {
    console.log(
      "     " +
        category.category +
        " " +
        "https://www.example.com/" +
        category.seo_name
    );
  }
}

This does look clunky and even worse, it doesn't work and there is no indentation.

Object example:

const json = {
  categories: [
    {
      category_id: "198",
      category: "Appliances",
      seo_name: "appliances",
      level:0
    },
    {
      category_id: "184",
      category: "Industrial Appliances",
      seo_name: "industrial-appliances",
      level:1
    },
  ],
  params: {
    visible: false,
    sort_order: "asc",
  },
};

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

0

How about using PRE and use the level to space it like suggested in a comment

const obj = { categories: [ { category_id: "198", category: "Appliances", seo_name: "appliances", level:0 }, { category_id: "184", category: "Industrial Appliances", seo_name: "industrial-appliances", level:1 }, { category_id: "187", category: "Appliances", seo_name: "appliances", level:2 }, ], params: { visible: false, sort_order: "asc", }, };

const container = document.querySelector('pre');
container.innerHTML = obj.categories
  .map(({level,category,seo_name}) => `${"".padStart(level,"\t")}${category} https://www.example.com/${seo_name}`)
  .join("\n")
<pre></pre>

about 4 years ago · Juan Pablo Isaza Relatório

0

You are assigning value inside your if condition using = instead of ==. Also, a much cleaner way is by using switch instead of if (atlease in this case and in my opinion), and use some loop so that you can easily change the number of spaces you can leave in your indentation anytime instead of counting it manually as you have in your code.

var data = [{ level: 0 }, { level: 1 }, { level: 1 }, { level: 2 }, { level: 2 }];

for (let element of data) {
  let result = "";
  switch (element.level) {
    case 1:
      for (let index = 0; index < 4; index++)
        result += " ";
      result += element.level;
      break;
    case 2:
      for (let index = 0; index < 8; index++)
        result += " ";
      result += element.level;
      break;
    default:
      result += element.level;
  }
  console.log(result)
}

about 4 years ago · Juan Pablo Isaza Relatório

0

var data = [{ level: 0 }, { level: 1 }, { level: 1 }, { level: 2 }, { level: 2 }];

for (let obj of data) {
  let result = "";
  result = ' '.repeat(obj.level * 4) + obj.level;
  console.log(result)
}

If you want one line.

var data = [{ level: 0 }, { level: 1 }, { level: 1 }, { level: 2 }, { level: 2 }];

data.forEach(obj => console.log(' '.repeat(obj.level * 4) + obj.level))

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