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.

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

Leave a Reply