create an object from an array in javascript

To create an object from an array in javascript, you can use the map() method in combination with arrow functions to transform each element of the array into an object property.

Here's an example:

index.tsx
const arr = ['John', 'Doe', 30];

const obj = {
    firstName: arr[0],
    lastName: arr[1],
    age: arr[2]
};

console.log(obj); // Output: { firstName: 'John', lastName: 'Doe', age: 30 }
190 chars
10 lines

In this example, we manually assigned each element of the array to a property of the object.

Alternatively, we can use the map() method to create a new array of objects from the initial array, like this:

index.tsx
const arr = [
  ['John', 'Doe', 30],
  ['Jane', 'Doe', 25],
  ['Bob', 'Smith', 45]
];

const objArr = arr.map(([firstName, lastName, age]) => ({firstName, lastName, age}));

console.log(objArr);
// Output: [
//   { firstName: 'John', lastName: 'Doe', age: 30 },
//   { firstName: 'Jane', lastName: 'Doe', age: 25 },
//   { firstName: 'Bob', lastName: 'Smith', age: 45 }
// ]
375 chars
15 lines

In this example, we used destructuring to extract each element of the nested arrays and create properties with corresponding names in the objects created by the map() method. We also used object shorthand notation to create objects with the desired properties.

gistlibby LogSnag