RJP RJP - 5 months ago 8
Javascript Question

Retrieving a property of a JSON object by index

I have a JSON Object as follows:

[
{
"Under 10": "0",
"10-20": "1",
"20-30": "3",
"30-40": "2",
"40-50": "4",
"50-60": "4",
"60-70": "1",
"Above 70": "0"
}
]


Is there anyway to access just individual properties of this object? I want to make each of them a separate JSON object.
I want it to look like this

[
{
"Under 10": "0"
},
{
"10-20": "1",
},
]


I tried using Oject.keys but it wasn't possible. I tried even with map function.

Answer

Using map:

var obj = YOUR OBJECT...

var a = Object.keys(obj[0]).map(function(key) {
  return {[key]: obj[0][key]}
});

quick demo: https://jsbin.com/mapoqo/1/edit?js,console