Tintin81
Tintin81

Reputation: 10215

How to get key values from nested JSON?

I have this JSON:

var json = [{'range':'2012','subtotal':'116.0','total_tax':'11.6','total':'127.6'},{'range':'2013','subtotal':'936.0','total_tax':'93.6','total':'1029.6'},{'range':'2014','subtotal':'368.0','total_tax':'36.8','total':'404.8'},{'range':'2015','subtotal':'267.0','total_tax':'26.7','total':'293.7'}];

How can I convert this into an array of ranges like this (using Javascript or jQuery):

['2012', '2013', '2014', '2015']

Thanks for any help.

Upvotes: 2

Views: 1399

Answers (4)

Richard Kho
Richard Kho

Reputation: 5286

You actually have an array of nested objects. Here are some options:

The naive solution would be to iterate over this array and push to a new array the values you want:

function getRange(arr) {
  var result = [];
  for (var i = 0; i < arr.length; i++) {
    result.push(arr[i].range)
  };
  return result;
}

You can also use the native Array.map method to do this easier:

  function getRange(arr) {
    return arr.map(function(elem) {
      return i.range;
    })
  }

Upvotes: 1

Mulan
Mulan

Reputation: 135406

First, that's not JSON, that's a JavaScript object literal. I'll refer to your data as data instead of json.

Second, let's use two reusable functions to express our intent more clearly

let map = f => x => x.map(f);
let prop = y => x => x[y];

Now, we simply map over your data and extract the property we want

map(prop('range'))(data);
// => ["2012","2013","2014","2015"]

Or we can define a reusable helper

let getRange = map(prop('range'));

getRange(data);
// => ["2012","2013","2014","2015"]

Here's the ES5 equivalent

var map = function map(f) {
  return function (x) {
    return x.map(f);
  };
};

var prop = function prop(y) {
  return function (x) {
    return x[y];
  };
};

var getRange = map(prop('range'));

getRange(data);
// => ["2012","2013","2014","2015"]

Upvotes: 2

Katana314
Katana314

Reputation: 8620

var mapped = json.map(function(obj) {
  return obj.range;
});

Also, minor point; what you have is an array. JSON is when an array/object is represented as a string (which happens to match the JavaScript literal notation of it)

Upvotes: 2

Etheryte
Etheryte

Reputation: 25325

You could simply use .map:

json.map(function(i) {
    return i.range;
});
//["2012", "2013", "2014", "2015"]

Upvotes: 4

Related Questions