Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
129 views
in Technique[技术] by (71.8m points)

javascript - Lint issue with for loop

The following logic works as intended. I have no means to change the lint rules.
data in this case is just an Object such as follows which gets passed in.

const testData = {
  item_one: 'item',
};

This is the function which takes in above data

const convert = (data) => {
  for (const key in data) {
      // ...
  }
  return data;
};

Getting lint errors as follows for my for loop as follows:

  1. for..in loops iterate over the entire prototype chain, which is virtually never what you want. Use Object.{keys,values,entries}, and iterate over the resulting array
  2. The body of a for-in should be wrapped in an if statement to filter unwanted properties from the prototype

To address point one, tried to switch the loop to be of type foreach as follows and that resolves the lint.
But that has broken my logic for some reason... Bit frustrating for logic to break due to lint.

data.forEach((previousKey) => {
    // ... same logic as above inside that loop loop
}

For point 2, I do want to iterate over every property. How could I resolve this lint error?

Please advice. Thank you.

question from:https://stackoverflow.com/questions/66067810/lint-issue-with-for-loop

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Only arrays have a forEach method; data.forEach won't work, since data isn't an array. You need this

data.forEach((previousKey) => {

to be

Object.keys(data).forEach((previousKey) => {

or, if you want the associated value too

Object.entries(data).forEach(([previousKey, value]) => {

For point 2, I do want to iterate over every property.

I don't think you deliberately want to iterate over inherited properties as well. Do you really have properties on internal prototypes, eg

const obj = Object.create({ foo: 'bar' });
obj.someProp = 'someVal';

, and you'd want to iterate over both foo and someProp?

That sounds quite unusual - possible, but very weird. That's why the linter is warning you against using for..in. If you do need to iterate over inherited properties, either disable the linter rule for this one line (preferable, since that'll make the code easiest), or (much more verbosely) iterate over the own-properties of the instance object with Object.keys, then do the same for the instance's prototype, and so on, until you reach the end of the prototype chain.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...