0

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

2
  • Well, you can hide the loop in a function… Commented Jun 10, 2013 at 12:08
  • 2
    That's not JSON, it's an object. You can use .map() to extract the values, but you'd need two .map() statements in a row to create both the ["Fiction","Thriller","Romance"] and [20,45,12] arrays, so I would guess a simple for loop would be more efficient. Commented Jun 10, 2013 at 12:10

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks a lot Bruno, I found the answer here (stackoverflow.com/questions/15783475/…) as well as soon as I was done posting :)
Surely a simple for loop would be more efficient than two .map() statements in a row? And it would end up with about the same amount of code to be typed... Using .map() is (arguably) "more elegant", but it doesn't win on "quick".
@nnnnnn You are correct a for loop is likely to be more efficient. However as xav was looking for an alternative to a for loop hence my suggestion. Nonetheless I think the idea to mention the performance implications is important. Thanks.
Well I gave you an upvote anyway, because like you said the OP was looking for a non-loop (or at least a non-explicit loop) solution. Just wanted to make sure performance got a mention too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.