最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论

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

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), {})
Share Improve this question asked Aug 14, 2018 at 1:03 Charles OkwuagwuCharles Okwuagwu 10.9k21 gold badges94 silver badges168 bronze badges 1
  • 2 This seems like an ESLint bug. It's not returning the assignment, because of the ma operator. – Barmar Commented Aug 14, 2018 at 1:51
Add a ment  | 

2 Answers 2

Reset to default 4

Personally I like code to be a bit more verbose, because one-liners look very clever today, but next week when I have to e 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);

you can use Object.assign

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

评论列表(0)

  1. 暂无评论