Skip to content
Advertisement

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",
  },
};

Advertisement

Answer

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))
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement