Search code examples
javascripteslintarrow-functions

how to fix Es-lint "no-return-assign" for the following line of code


This code runs correctly (converting an array of objects into an object of objects)

ES-lint however gives this error:

[eslint] Arrow function should not return assignment. (no-return-assign)

Please how may this be re-written to satisfy es-lint

var x = arr.reduce((obj, item) => (obj[item.userid] = item, obj), {})

Solution

  • Personally I like code to be a bit more verbose, because one-liners look very clever today, but next week when I have to come back and fix a bug in that very same place, it will take me a while to understand what I was doing, not to mention if it's someone else who has to fix it.

    This is how I would write it:

    var x = arr.reduce((obj, item) => {
        obj[item.userid] = item;
        return obj;
    }, {});
    

    Here you have a snippet with some dummy data to test it.

    var arr = [
            {userid: 11},
            {userid: 12},
            {userid: 13},
            {userid: 14},
        ];
    
    var x = arr.reduce((obj, item) => {
        obj[item.userid] = item;
        return obj;
    }, {});
    
    console.log(x);