Skip to main content
2 of 2
Explain the chaining approach
Phil W
  • 38.1k
  • 5
  • 53
  • 106

An alternative to @Rohit's approach is to use Array.reduce functionality:

const arrayObj = [{"Id":"0QL8W000006RHl1WAG","Sortorder":"1"}, {"Id":"0QL8W000006RHl0WAG","Sortorder":"2"}, {"Id":"0QL8W000006RHl2WAG","Sortorder":"3"} ];

const result = arrayObj.reduce(
    (target, item) => (target[item.Id] = item.Sortorder, target),
    {});

The {} is the initial empty object to return (what becomes the target in the reducer), while the "reducer function" simply:

  1. Sets the property on that object with the name taken from the item's Id and sets it to the item's Sortorder (target[item.Id] = item.Sortorder) then
  2. Uses the comma operator to ensure that the function returns the target object for the reducer chaining (, target).

By "chaining" the target object in this way, this avoids creating garbage that must be collected - we simply add properties to that one JavaScript object.

Phil W
  • 38.1k
  • 5
  • 53
  • 106