Key of object from eager loading by specific field


#1

Hello,

is there any way to set key of object loaded by eager loading? For example, I have two database tables:

  1. pages
  2. page_translations

In my Page model I have:

translations () {
    return this.hasMany('App/Models/PageTranslation');
}

When I do await Page.query().with('translations').fetch(); My output is:

{
    id: 1,
    translations: [
        {
            language: 'cs'
            title: 'Moje první stránka',
            slug: 'moje-prvni-stranka'
        },
        {
            language: 'en',
            title: 'My first page',
            slug: 'my-first-page'
        }
    ]
}

Is there any way to get output like this?

{
    id: 1,
    translations: {
        cs: {
            language: 'cs'
            title: 'Moje první stránka',
            slug: 'moje-prvni-stranka'
        },
        en: {
            language: 'en',
            title: 'My first page',
            slug: 'my-first-page'
        }
    }
}

Thank you for your answers.


#2

Have to do it manually by looping over the data


#3

You can create a function to do it :

function ArrayToObject(array, key) {
  return array.reduce((obj, item) => {
    obj[item[key]] = item

    return obj
  }, {})
}

… and use it like that : ArrayToObject(yourArray, ‘language’)

Of course, you can edit this function to check if the desired key exists and throw an exception if not. Same thing for items, they have to be objects.