Convert array to object

Hello,

Thanks in advance for the help, I’m currently a student developer and really having a hard time with my assignments. Here is the most recent and its simply converting an array into an object. I there is someone that wouldn’t mind be a mentor that would be extremely helpful.

function main(objArr)  {
    // console.log(objArr)
    let newObj = new Object();
    console.log(newObj)
    
    for (let i = 0; i < objArr.length; i++) {
        // newObj.push()
        if (objArr[i] % 2 === 1) {
        objArr.push(newObj)
            console.log(objArr)
        }       
    }
}
  
  main(['Yoghurt', 48, 'Rice', 138, 'Apple', 52])  // { Yoghurt: 48, Rice: 138, Apple: 52 }
1 Like

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

I don’t have the full context of the assignment that you are trying to achieve, but it looks to me like you want to convert a structured array into an object map. You do have to iterate over the array and pick the right indexes to extract the key and values. I can tell there’s an error in your loop statement and the main function isn’t returning or logging anything after the loop.

Hi,
Here your code with some adjustments!

function main(objArr)  {
    // console.log(objArr)
    let newObj = new Object();
    console.log(newObj)
    
    for (let i = 0; i < objArr.length; i++) {
        // newObj.push()
        if (objArr[i] % 2 === 0) {
        newObj[i] = objArr[i];      
        }       
    }
  return newObj;
}

I hope it helps!

Okay, cool. This was my first post and I’m looking forward to being apart of the community. Thanks for the heads up!

Yes, I was trying to convert the input into an object.

Thanks, Moriel. This was very helpful. I’m going to spend some time debugging this.

Hi,

I did only so far, because I am not allowed to provide full solutions!

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.