Hexana Hexana - 2 months ago 8
Javascript Question

Display Specific Categories in Javascript Multi-Dimensional Array

I am trying to return a unique list of key value names in a javascript array. I have only been able to specify the array index but I would like to return all the category names in the whole array. I keep getting undefined.

This is what I have tried:

var Foods = {
"Fruits": [
{
"id": "1",
"Name": "Granny Smith",
"Category": "Apple"},
{
"id": "2",
"Name":"Raspberries",
"Category": "Berries"}
],

"Potatoes": [
{
"id": "3",
"Name":"Maris Piper",
"Category": "White"}
{
"id": "4",
"Name":"Charlotte",
"Category": "Baby"}
]}

for(var categories in Foods) {
var cats = Foods[categories][1].Category;
document.write(cats);
}


Ideally I would like to be able to return:

Apple
Berries
Baby
White

Any help appreciated.

Cheers

Answer Source

You can implement Array#forEach function inside your for...in loop. Then save it in e.g. array or basically log it.

for (let item in Foods) {
  Foods[item].forEach(v => console.log(v.Category));
}

Snippet:

var Foods = {
  "Fruits": [{
      "id": "1",
      "Name": "Granny Smith",
      "Category": "Apple"
    },
    {
      "id": "2",
      "Name": "Raspberries",
      "Category": "Berries"
    }
  ],
  "Potatoes": [{
    "id": "3",
    "Name": "Maris Piper",
    "Category": "White"
  }, {
    "id": "4",
    "Name": "Charlotte",
    "Category": "Baby"
  }]
}, names = [];

for (let item in Foods) {
  Foods[item].forEach(v => names.push(v.Category));
}

console.log(names);