简体   繁体   中英

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), {})

您可以使用Object.assign

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

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 took 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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM