Search code examples
javascriptarraysfor-loopobjectfor-in-loop

Array to Object?


I am a beginner programming student and I have some doubts about how to focus and understand this exercise.

Anyone could explain me the logical to face this exercise?

I have an array like this: ['Queen', 'Elizabeth', 'Of Hearts', 'Beyonce'] and I want this result: { Queen : 'Beyonce' }

I want to make function to return the following:

  1. the first element of the array as the object's key
  2. the last element of the array as that key's value. I am doing a var key in array and then a loop through the array

function transformFirstAndLast(array) {
  for (var key in array) {
    for (var i = 0; i < array.length; i++) {
      Object.key[0]
    }
  }
}


Solution

  • let data = ['Queen', 'Elizabeth', 'Of Hearts', 'Beyonce'] ;
    
    let myobj={}
    myobj[data.shift()] = data.pop();
    
    console.log(myobj);