Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

168
Views
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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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;
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!