1

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!

2 Answers 2

3

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the ultra-fast answer, @Aknosis - this was exactly the information I needed.
0

You need to use the "value" option.

like:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.