Is it possible to create an object out of each element of an array?

Viewed 58

I'm still learning JS, I come from coding in C, I'm sorry if this is all wrong or outright senseless.

My program will work based on user input, meaning I have no control over how many and what names I will get. I will explain it in steps:

First step: it asks how many instances of elements and properties we're working with, let's say 2 for elements and 4 for properties. (x = 2, y = 4)

Second step: it asks for the names like this:

Insert names for elements: (x slots) let's say: "Ice Cream" and "Juice"
Insert names for properties: (y slots) let's say: "Strawberry", "Vanilla", "Chocolate", "Mango"

It then saves these two as arrays:

Array1 =["Ice Cream", "Juice"]
Array2 = ["Strawberry", "Vanilla", "Chocolate", "Mango"].

What do I want to do?

I want to make an object out of each array element of Array 1. Such as: const "Ice Cream" { properties: (will get from boolean input afterwards based on array 2) }

I was thinking about iterating for each, but I wasn't sure about how to convert each element into its own object for later usage.

In short, I want to go from Array1 = ["Ice Cream", "Juice"] to an array of objects named after the strings contained within itself, showcasing how I think it'd be: Array1 (now objects) = [Ice_Cream{properties}, Juice{properties}]

2 Answers

If you want to convert the elements of the array into an object I would suggest Array#map.

const array1 = ["Ice Cream", "Juice"];
const array1Obj = array1.map((item) => {
    return {
             [item]: { taste: "good", ingredients: ["ice", "cream"] }
           };
});

However you might also consider converting your array into an object itself. This can be done with Array#reduce.

const array1 = ["Ice Cream", "Juice"];
const array1Map = array1.reduce((map, item) => {
    map[item] = { a: "b"}; // assign key of item to a value of object and add properties
    return map;
}, {});

This way you could look up "Ice Cream" or "Juice" on array1Map like array1Map["Ice Cream"]

One possible solution (see code comments)

let array1 = ["Ice Cream", "Juice"];
let array2 = ["Strawberry", "Vanilla", "Chocolate", "Mango"];

let arrayOfCombinedObjects = [];

//iterate over array1
for(let arr of array1) {
    //create object
  let arrObject = {[arr]: {}};
  
  //iterate over array2
  for(let i = 0; i < array2.length; i++) {
    let arr2 = array2[i];
    //add keys to object
    arrObject[arr]['key' + i] = arr2;
  }
  
  console.log(arrObject);
  
  //add newly created object to our object array
  arrayOfCombinedObjects.push(arrObject);
}

console.log(arrayOfCombinedObjects);

Related