Jacob Gunther
Jacob Gunther

Reputation: 361

Get name of JavaScript Multi-dimensional array, not children

I have a JavaScript multi-dimensional array that had multiple values with a ton of sub-values. Here's what I mean:

var items = {
    "Area": [
        "Feet",
        "Meters"
    ],
    "Frequency": [
        "Hertz",
        "Kilohertz"
    ]
};

I want to cycle through each first dimension item (like Area and Frequency). I do not wanna cycle through sub-values but get the name of the first dimension values.

Here's my code to cycle:

$(function() {
    $.each(items, function(index) {
        $(".category").append("<option>" + items[index].text + "</option>");
    });
});

Just to be sure, I want to get the names of each first-dimension values, like Area and Frequency. I've tried things like .text, .val, .val() (jQuery), .innerHTML, etc but nothing seems to work.

EDIT: Putting nothing after items[index] just returns the sub-values to each first dimension items.

Upvotes: 0

Views: 577

Answers (2)

Aniket Sahrawat
Aniket Sahrawat

Reputation: 12937

When you do items[index], it means you are referencing to value of items. index is the key and items[index] is the value. Try this code:

var items = {
  "Area": [
    "Feet",
    "Meters"
  ],
  "Frequency": [
    "Hertz",
    "Kilohertz"
  ]
};
$(function() {
  $.each(items, function(index, value) {
    $(".category").append("<option>" + index + "</option>");
    console.log(index);
    console.log(value);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 1

JVDL
JVDL

Reputation: 1202

What you have rather than a multi-dimensional array is an object (or map, hashmap, whatever it's called in other languages ;))

To get all the keys you can use Object.keys(myObj);

var items = {
    "Area": [
        "Feet",
        "Meters"
    ],
    "Frequency": [
        "Hertz",
        "Kilohertz"
    ]
};

var keys = Object.keys(items);
console.log(keys);

// iterate through them
keys.forEach(function(item, index) {
  console.log(index, item);
});

Upvotes: 3

Related Questions