-3

I am beginner please help me to get value from the below array json object.

[{"Category":"HI","Sub Category":"AQ HIOP"},
{"Category":"2HJ","Sub Category":"AS HIOP"},
{"Category":"3HJ","Sub Category":"AT HIOP"},
{"Category":"4Hj","Sub Category":"AP HIOP"},
{"Category":"5HJ","Sub Category":"AN HIOP"},
]

I would just need the value of Sub Category

Thanks in Advance.

Dython
  • 134
  • 4
  • 12

3 Answers3

1

You have multiple ways to do it. If you have your Object in a variable you can access like this:

var test = [{"Category":"HI","Sub Category":"AQ HIOP"},
{"Category":"2HJ","Sub Category":"AS HIOP"},
{"Category":"3HJ","Sub Category":"AT HIOP"},
{"Category":"4Hj","Sub Category":"AP HIOP"},
{"Category":"5HJ","Sub Category":"AN HIOP"},
]

test[0]["Sub Category"] //Take into account that you have an array

In the case that you don't have any space in the key you can access like this:

test[0].Category;

If your JSON is string you must use JSON.parse before.

Edit

Here you have how to insert to a new array

var another_array = []
another_array.push({"New category": test[0]["Sub Category"]})
halfer
  • 19,824
  • 17
  • 99
  • 186
Brank Victoria
  • 1,447
  • 10
  • 17
1

Try this:

var arr = [{"Category":"HI","Sub Category":"AQ HIOP"},
    {"Category":"2HJ","Sub Category":"AS HIOP"},
    {"Category":"3HJ","Sub Category":"AT HIOP"},
    {"Category":"4Hj","Sub Category":"AP HIOP"},
    {"Category":"5HJ","Sub Category":"AN HIOP"},
    ]
    for (var i = 0; i < arr.length; i++) {
     for (key in arr[i]) {
      console.log('Key: '+ key + ' Value: ' + arr[i][key]);
     }
    }

You can use for and for in to access to your Objet

0
var test = [
{"Category":"HI","Sub Category":"AQ HIOP"},
{"Category":"2HJ","Sub Category":"AS HIOP"},
{"Category":"3HJ","Sub Category":"AT HIOP"},
{"Category":"4Hj","Sub Category":"AP HIOP"},
{"Category":"5HJ","Sub Category":"AN HIOP"},
];
test.forEach(function(item){
    console.log(item);
})