Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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}]

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading