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:
- Sets the property on that object with the name taken from the item's
Id
and sets it to the item'sSortorder
(target[item.Id] = item.Sortorder
) then - 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.