skip to Main Content

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


  1. 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().

    Login or Signup to reply.
  2. The documentation indicates that you can exit the _.forEach() early by explicitly returning false which your arrow function does via an implicit return.

    Iterates over elements of collection and invokes iteratee for each element. The iteratee is invoked with three arguments: (value, index|key, collection). Iteratee functions may exit iteration early by explicitly returning false.

    Because you have not enclosed the body of your arrow function it implicitly returns the evaluated value of the body; c.used = false evaluates to false which is then returned and exits the forEach.

    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 the forEach to complete as expected.

    _.forEach(this.colors, c => {c.used = false});
    

    see: When should I use a return statement in ES6 arrow functions for discussion of returning from an arrow function.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search