简体   繁体   中英

no-return-assign when mapping over object values

I am trying to create an object whose keys and values are the keys of a different object. However I am getting a linting error:

ESLint: Arrow function should not return assignment.(no-return-assign)

在此处输入图片说明

const obj = {
  a: 1, b: 2, c: 3,
};
const options: {[key: string]: string} = {};
Object.keys(obj).map(i => options[i] = i);

JS 101. When you use an arrow function without brackets, you should always put a returned value on the right side. If you want to run options[i] = i , you should put brackets around it and use forEach instead of map . map returns another array that contains all the returned values from the provided function inside.

Fix it as follows.

Object.keys(obj).forEach((i) => {
  options[i] = i;
});

However, since you say you want to create an object with keys and values from the values and keys of another object, you may use the following codes.

options = Object.keys(obj).reduce((prev, current) => {
  return {
    ...prev,
    current: obj[current],
  };
}, {});

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