Skip to content

arrayToObject

Yousif Al-Raheem edited this page Feb 12, 2020 · 5 revisions

This utility converts an array to an object. To use it, pass the array and an optional the desired field name to be injected into the object keys (Array keys are numbers starting with 0).

Example

const arr = [
    { first: 1, second: 2 },
    { first: 3, second: 4 },
    { first: 5, second: 6 },
];
const result = arrayToObject(arr, "item");
console.log(result);

Output

{
    item0: { first: 1, second: 2 },
    item1: { first: 3, second: 4 },
    item2: { first: 5, second: 6 },
}

Properties

Param Type Description
array Array The target array
keyField? string The key to be used as identifier for each key of the new object

Clone this wiki locally