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

Function to convert array of strings into array of objects

I am having trouble with a function question for my course.

Write a function that converts an array of strings into an array of objects, with the supplied key

E.g.

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

arrayToObjects(["Mike", "Emily"], "name") // => [{ name: "Mike" }, { name: "Emily"}]
function arrayToObjects(array, key) {
    const objArr = [] // to return an array later.
    this.key = key
    for (let i = 0; i < array.length; i++) {
        const o = new Object()
        o.key = array[i]
        objArr.push(o)
        return objArr
    }
}

arrayToObjects(['Mike', 'Emily'], 'name')

If I pass the array values and key string I log this:
[ { key: ‘Mike’ }, { key: ‘Emily’ } ]

I can’t get the key name into the constructor from the function argument.

>Solution :

Change the following line :

o.key = array[i] 
//change
o[key] = array[i]
function arrayToObjects(array, key) {
    const objectArray = []; // To return an array later.
    this.key = key;
    for (const element of array) {
        const o = new Object();
        o[key] = element;
        objectArray.push(o);
    }
   return objectArray;
}
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