I need to reduce an array of objects, but reduce on a specific key
property in the object, and have all objects with the same key
value placed into an array in the associated value
array.
An example of what I need:
Objects
var obj1 = {
name: "server1",
type: "http",
port: "8080"
}
var obj2 = {
name: "server2",
type: "https",
port: "8443"
}
var obj3 = {
name: "server3",
type: "http",
port: "80"
}
// Place objects in an array (as interm step)
var array = [obj1, obj2, obj3];
With the above code, I tried
var map = new Map(array.map(server => [server.type, server]));
but this ends up giving me:
0: {"http" => Object}
key: "http"
value:
name: "server3"
port: "80"
type: "http"
1: {"https" => Object}
key: "https"
value:
name: "server2"
port: "8443"
type: "https"
but what I need is:
0: {"http" => Object}
key: "http"
value:[
{
name: "server1"
port: "8080"
type: "http"
},
{
name: "server3"
port: "80"
type: "http"
},
1: {"https" => Object}
key: "https"
value:
name: "server2"
port: "8443"
type: "https"
So I can go through each type
, find all unique values, create lists of each object with this as a type, then add this to a map but it seems too much for a simple task.
Is there a faster/more convenient way to shorten this?