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

How to make an array of objects from an array of elements

This is driving me crazy.

I have an array like so:

myArray = ['A', 'B', 'C', 'D', 'E', 'F', ];

and my code is making a NEW object that will look like this:

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

myNewObj = [
 {
   name: "A",
   displayName: "A"
 },
 {
   name: "B",
   displayName: "B"
 },
 {
   name: "C",
   displayName: "C"
 },
 {
   name: "C",
   displayName: "C"
 },
 {
   name: "D",
   displayName: "D"
 },
 {
   name: "E",
   displayName: "E"
 },
 {
   name: "F",
   displayName: "F"
 }
]

My code gets values in the myArray and I want to create myNewObj

This is how I’m doing it so far

I create the new object

let newObj = [{
    "name": "",
    "displayName": ""
}];

Then I use a simple FOR NEXT loop and it work up until a point and claims newObj[i].name IS UNDEFINED… how is that possible when I’m defining it and see it in the Google dev console?

            for (let i = 0; i < myArray.length; i++) {
                newObj[i].name = myArray[i];
                newObj[i].displayName = myArray[i];

                myNewObj.push(newObj);
            }

However, I consistently get this error:

newObj[i].name is NOT DEFINED and it dies.

>Solution :

Using Array#map:

const myArray = ['A', 'B', 'C', 'D', 'E', 'F'];

const myNewArray = myArray.map(e => ({ name: e, displayName: e }));

console.log(myNewArray);

Your solution (you need to initialize the array as [] and create a new object in every iteration to push it):

const myArray = ['A', 'B', 'C', 'D', 'E', 'F'];

const myNewArray = [];

for (let i = 0; i < myArray.length; i++) {
  const obj = {};
  obj.name = myArray[i];
  obj.displayName = myArray[i];
  myNewArray.push(obj);
}

console.log(myNewArray);
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