Convert a flat data to hierarchical data
by marbx
JavaScript
var arry = [
{
userId: 1,
userEmail: '[email protected]',
postId: 1,
postBody: 'User 1\'s first post',
},
{
userId: 1,
userEmail: '[email protected]',
postId: 2,
postBody: 'User 1\'s second post',
},
{
userId: 2,
userEmail: '[email protected]',
postId: 3,
postBody: 'User 2\'s first post',
},
];
function createPost(obj) {
post = {};
post.postId = obj.postId;
post.postBody = obj.postBody;
return post;
}
function convert(array) {
var map = {};
for (var i = 0; i < array.length; i++) {
var currentObject = array[i];
if (!map[currentObject.userId]) {
obj = {}
obj.userId = currentObject.userId;
obj.userEmail = currentObject.userEmail;
obj.posts = [];
map[obj.userId] = obj;
}
obj.posts.push(createPost(currentObject));
}
var keys = Object.keys(map);
return keys.map(function (v) { return map[v]; });
}
var r = convert(arry)
console.log(r);