I was trying to set a boolean property for every object of an array.
import { Component, OnInit } from "@angular/core";
import * as _ from "lodash";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
title = "CodeSandbox";
colors: {hex: string, used: boolean}[] = [
{hex: "#ff0000", used: true},
{hex: "#00ff00", used: true},
{hex: "#0000ff", used: true}
]
ngOnInit() {
_.forEach(this.colors, c => c.used = false);
console.log(this.colors);
}
}
Apparently only the first object is affected. This is the output.
0: Object
hex: "#ff0000"
used: false
1: Object
hex: "#00ff00"
used: true
2: Object
hex: "#0000ff"
used: true
Here is the sandbox: https://codesandbox.io/s/strange-water-p19ihj?file=/src/app/app.component.ts
It works with _.map and with native forEach. Am I missing something or is it a bug?
2
Answers
The _.forEach() method only iterates over own enumerable string keyed properties of an object.
The used property is not an own enumerable string keyed property of the objects in your colors array, but rather an enumerable property inherited from the Object prototype and in lodash version 4, only the first object is affected when you use _.forEach().
The documentation indicates that you can exit the
_.forEach()
early by explicitly returningfalse
which your arrow function does via an implicit return.Because you have not enclosed the body of your arrow function it implicitly returns the evaluated value of the body;
c.used = false
evaluates tofalse
which is then returned and exits theforEach
.Surrounding the body with braces will avoid the arrow function’s implicit return (it will now return
undefined
as any function with no return statement would) and thus allow theforEach
to complete as expected.see: When should I use a return statement in ES6 arrow functions for discussion of returning from an arrow function.