0

Here is my object

var myObject = {"HardGood":362,"Music":2};

console.log(myObject[0]); // undefined? instead of "Hardwood 362"

What am I doing wrong?

Jason
  • 931
  • 2
  • 12
  • 26

3 Answers3

3

myObject is an object not an array, so using [0] will indeed be undefined. Use myObject.HardGood or myObject.Music to get the value or that property

Code

console.log(myObject.HardGood); // will output 362
console.log(myObject.Music); // will output 2

UPDATE

var objects = [
    {
       "title": "HardGood"
       "type": "362"
    },
    {
       "title": "Music"
       "type": "2"
    }
];

console.log(objects[0].title); // output HardGood
console.log(objects[1].type); // output 2
Mivaweb
  • 5,580
  • 3
  • 27
  • 53
  • Thankyou, how do I obtain the HardGood & Music? because the object will change and it will be difficult to hardcode all of the different items. – Jason Jul 03 '15 at 13:15
  • @Jason view my update with an example that you will understand better – Mivaweb Jul 03 '15 at 13:20
  • Hi, I get where you are coming from, but I have no control over the structure of the object, unfortunately it arrives as var myObject = {"HardGood":362,"Music":2}; not as in your example. I am having a brain fade today, so if I am missing something, please let me know, many thanks – Jason Jul 03 '15 at 13:29
0

You should call the first element in an object like this: myObject.key and your key is HardGood.

In arrays it's done like this:

var _Array = [];
_Array .push('x1'); //pushing in array
_Array .push('x2');

console.log(_Array[0]); // getting the first element in that array

Update: if you want to get it dynamically:

    var myObject = {"HardGood":362,"Music":2};

    for(var key in myObject){
      console.log(key +':'+myObject[key]);
    }
Abude
  • 2,112
  • 7
  • 35
  • 58
0

You have to access JSON object property with . Like below

var myObject = {"HardGood":362,"Music":2};
console.log(myObject.HardGood); //362

Useful links Have a look at below links to understand it better.

Javascript-property-access-dot-notation-vs-brackets

JS-dot-notation-vs-bracket-notation

MDN - OperatorsProperty_Accessors

Community
  • 1
  • 1
SK.
  • 4,174
  • 4
  • 30
  • 48