Skip to content

Instantly share code, notes, and snippets.

@mhkeller
Last active December 10, 2015 04:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mhkeller/4384356 to your computer and use it in GitHub Desktop.
Save mhkeller/4384356 to your computer and use it in GitHub Desktop.
Nesting a JSON object using a value in the data. Cross-browser replacement for d3.nest() .key() .entries()
http://jsfiddle.net/mhkeller/ezvuB/
var sets = [
{
"uid": "a1",
"quote": "hey",
"source": "facebook"},
{
"uid": "a1",
"quote": "yo",
"source": "facebook"},
{
"uid": "a2",
"quote": "yo",
"source": "facebook"}]
var nested = {};
for (var set in sets) {
if (sets.hasOwnProperty(set)) {
// If this value is new, make it the key of a new array
if (!nested[sets[set].uid]) {
nested[sets[set].uid] = new Array;
}
var key = sets[set].uid;
var entry = sets[set];
// Get rid of the attribute that is the key
delete entry.uid
// Create the nested object
nested[key].push(entry)
}
}
console.log('nested', nested)​
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment