メモ。

Javascript の for...in 文中での要素の追加・削除について。

for...in - JavaScript | MDN

A for...in loop iterates over the properties of an object in an arbitrary order (see the delete operator for more on why one cannot depend on the seeming orderliness of iteration, at least in a cross-browser setting). If a property is modified in one iteration and then visited at a later time, its value in the loop is its value at that later time. A property that is deleted before it has been visited will not be visited later. Properties added to the object over which iteration is occurring may either be visited or omitted from iteration. In general it is best not to add, modify or remove properties from the object during iteration, other than the property currently being visited. There is no guarantee whether or not an added property will be visited, whether a modified property (other than the current one) will be visited before or after it is modified, or whether a deleted property will be visited before it is deleted.

簡単にまとめれば、

  • まだ訪れていないプロパティを削除すると、そのプロパティは残りのループでも訪れられることはない
  • プロパティを新たに足した場合は、それが訪れられるかは分からない
  • 現在のプロパティ以外を操作(削除・追加・変更)するのは避けたほうが無難

for ... in 文中で現在のプロパティを delete するのは完全に valid っぽい。

for (key in obj) {
  if (toBeDeleted(obj[key])) {
    delete obj[key];
  }
}