RJP
RJP

Reputation: 405

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.

Upvotes: 0

Views: 114

Answers (4)

Anson
Anson

Reputation: 489

The original JSON is an Array and we need to convert the first Object in the Array to a new Array. As below,

// Original JSON, an Array.
var raw = [ 
  {
    "Under 10": "0",
    "10-20": "1",
    "20-30": "3",
    "30-40": "2",
    "40-50": "4",
    "50-60": "4",
    "60-70": "1",
    "Above 70": "0"
  }
];

// The first Object in original JSON(an Array).
var oldObject = raw[0]; 

// New Array stores the Objects you want.
var newArray = []; 

// Get each item in oldObject
for(var key in oldObject) { 

  // Create a new Object
  var obj = {}; 

  // Assign the value of key of oldObject to obj[key].
  // Like obj["Under 10"] = "0".
  obj[key] = oldObject[key];  

  // Append obj to newArray.
  newArray.push(obj);

}

Anyway, newArray is what you need. Cheers :)

Upvotes: 0

Naga Sai A
Naga Sai A

Reputation: 10975

To achieve your expected result,below option might help you

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

    var keys =Object.keys(x[0]);
    var final=[];

    for(i=0;i< keys.length;i++){
     final[i] = '[{'+keys[i]+':'+x[0][keys[i]]+'}]';

    }


    console.log(final);//final array will have expected result

Codepen- http://codepen.io/nagasai/pen/KMMbMm

Upvotes: 0

le_m
le_m

Reputation: 20228

You can use Object.getOwnPropertyNames() or Object.keys(). The former returns all own properties while the later is a bit more specific and returns only the enumerable properties. For JSON it shouldn't matter, though.

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

var result = Object.getOwnPropertyNames(json[0]).map(name => ({[name]: json[0][name]}));

console.log(result);

Upvotes: 3

omarjmh
omarjmh

Reputation: 13888

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

Upvotes: 2

Related Questions