Array to Object?

Viewed 169

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

3 Answers

let data = ['Queen', 'Elizabeth', 'Of Hearts', 'Beyonce'] ;

let myobj={}
myobj[data.shift()] = data.pop();

console.log(myobj);

Hey the way to do this would be using a very simple using a bit of code

function assignObj() {
    object.key = myArray[0];
    object.value = myArray[myArray.length-1];
}

There is no need for a forloop. Unless you need to do that then it is more complicated . Anyways hope this helps. :)

Arrays are not intended to be used like this. I would highly discourage using this in real life. But this is how you can do it.

  • create an object
  • set the first item of the array as key
  • set the last item of the array as a value
  • return the new object

const array = ['Queen', 'Elizabeth', 'Of Hearts', 'Beyonce'];
console.log( compose_object(array) );
 
function compose_object(  array ) {
  let result = new Object();
  result[array[0]] = array[array.length-1];
  return result;
}

Related