Smoothing an array of objects into another array of objects using javascript

I ran into this problem in different contexts and languages, and I always managed to get around this, but I would like to finally find the right template for this. This is due to joining SQL tables. Usually I made two calls: one for elements and one for comments, but I know that there is a way to get all this in one call, and then smooth out the result.

What I would like to do is take an array that looks like this:

[ { itemId: 1, comments: { commentId: 1 } }, { itemId: 1, comments: { commentId: 2 } }, { itemId: 2, comments: { commentId: 3 } } ] 

And include it in this:

 [ { itemId: 1, comments: [ { commentId: 1 }, { commentId: 2 } ] }, { itemId: 2, comments: [ { commentId: 3 } ] } ] 
+6
source share
2 answers

The following should work for you:

 function combine(arr) { var newObj = {}; // combine the comments for (var i=0; i < arr.length; i++) { if (newObj[arr[i].itemId]) { newObj[arr[i].itemId].push(arr[i].comments); } else { newObj[arr[i].itemId] = [arr[i].comments]; } } // make the list var keys = Object.keys(newObj); return keys.map(function(key){return {itemId: key, comments: newObj[key]} }) } 
+1
source

You can also use filter() :

 function combine(src) { var dict = {}; return src.filter(function(item) { if (!dict[item.itemId]) { item.comments = [ item.comments ]; dict[item.itemId] = item; return true; } else { dict[item.itemId].comments.push(item.comments); return false; } }); } 
+1
source

Source: https://habr.com/ru/post/946642/


All Articles