xav
xav

Reputation: 4251

Extract array from one json variable

My question seems so simple to me that I cannot figure why I could not find an answer on the web. Really sorry in advance if this has been answered a thousand times, maybe I just don't have the wording right.

I am working with json formatted data in d3.js.

dataset = [
    {"category":"Fiction", "popularity":20},
    {"category":"Thriller", "popularity":45},
    {"category":"Romance", "popularity":12}
];

From all I know, some of the d3.js functions require a simple array.

Example 1: for a bar chart, my d3.scale.ordinal().domain(data) needs an array with ["Fiction", "Thriller", "Romance"]

Example 2: for a pie chart, the d3.layout.pie(data) function needs an array with [20,45,12]

These functions force me to extract all the values from "category" or "popularity" into one-dimensional array via simple for loop, which seems quite dumb.

Is there a more elegant and quick solution to extract an array with the values of one variable from a json?

Thanks a lot for your help! Xavier

Upvotes: 0

Views: 226

Answers (1)

Bruno
Bruno

Reputation: 5822

Use

var category = dataset.map( function( obj ) { return obj.category; } );
var popularity = dataset.map( function( obj ) { return obj.popularity; } );

The category and popularity arrays will contain the values you need.

However, a for loop is likely to be a faster implementation.

Upvotes: 3

Related Questions