Last active
December 10, 2015 04:58
-
-
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()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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