0

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.

pilchard
  • 12,414
  • 5
  • 11
  • 23
Mayur Kumar
  • 67
  • 1
  • 5
  • also see: [Is it possible to add dynamically named properties to JavaScript object?](https://stackoverflow.com/questions/1184123/is-it-possible-to-add-dynamically-named-properties-to-javascript-object) – pilchard Dec 29 '21 at 12:23
  • 1
    Using [`.map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) would make this much easier/shorter: `function arrayToObjects(array, key) { return array.map(value => ({ [key]: value })); }` – RoToRa Dec 29 '21 at 14:57

1 Answers1

2

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;
}
milad shiriyan
  • 296
  • 1
  • 9