Aggregating an array of objects into an object

I have an array of objects like this:

[
    {
        "path": [
            "attributes"
            "redirectUri"
        ],
        "message": "must be an absolute URI.",
    },
    {
        "path": [
            "attributes"
            "redirectUri"
        ],
        "message": "blabla",
    },
    {
        "path": [
            "attributes"
            "anotherField"
        ],
        "message": "second",
  }
]

I’d like to parse it and produce an object like this:

{
  redirectUri: "must be an absolute URI., blabla",
  anotherField: "second"
}
  1. map and join message for the same path[1], separated by comma
  2. take into account only path[1] as the key

any help would be greatly appreciated.

I did not go very far, I can do this in ruby but not in javascript, for now I’m trying

const errorObject = result.data.appCreate.errors
  .map(obj => ({ [obj.path[0]]: obj.message })) 

but I’m looking at reduce

Answer

You iterate through each term using Array#reduce, this lets us keep a new object with the result. We can also use Destructuring assignment to get the exact properties that we need.

let arr = [ { path: ['attributes', 'redirectUri'], message: 'must be an absolute URI.', }, { path: ['attributes', 'redirectUri'], message: 'blabla', }, { path: ['attributes', 'anotherField'], message: 'second', }, ];

let res = arr.reduce((acc, { path: [, tag], message }) => {
  acc[tag] = acc[tag] ? acc[tag] + ', ' + message : message;
  return acc;
}, {});

console.log(res);