BNetz
BNetz

Reputation: 361

Loop over nested objects

Found several threads to this theme, but was not able to solve my problem with them.

I have an object like this one:

 allItems: {
            item1: {
                val1: 4,
                val2: 'blaharb'
                   },
            itemxyz2: {
                val1: 76,
                val2: 'blurb'
                   }
           }

Now I simply want to put out a list like

item1 has 4 for val1 and blaharb for val2
itemxyz2 has 76 for val1 and blurb for val2

My tries so far:

console.log(allItems.item1.val1); // prints correctly '4' in the console

$.each(allItems, function(key, value) {
 console.log(key); // gives me correct key (like 'item1')
 console.log(allItems.item1.val1);// error: "undefined is not an object" - but why?!
console.log(allItems.key.val1); // same error, understandable ...
});

Would appreciate help very much, thanks!

Upvotes: 1

Views: 68

Answers (2)

G. Nachtigal
G. Nachtigal

Reputation: 41

You need to use the "value" option.

like:

  $.each(allItems, function(key, value) {
            console.log(key, value.val1);
            console.log(key, value.val2);
  });

Upvotes: 0

aknosis
aknosis

Reputation: 4348

You can access your object properties with array syntax:

$.each(allItems, function(key, value) {
  console.log(allItems[key]["val1"]);
  console.log(allItems[key]["val2"]);
});

Example:

var allItems = {
  item1: {
    val1: 4,
    val2: 'blaharb'
  },
  itemxyz2: {
    val1: 76,
    val2: 'blurb'
  }
};


$.each(allItems, function(key, value) {
  console.log(allItems[key]["val1"]);
  console.log(allItems[key]["val2"]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 3

Related Questions