1

I've been looking javascript for about half a year now but I've encountered something I'm a bit puzzled by. I haven't done this before so I'm not sure what's going on here. I'm trying to make a new object in a for loop of another object. When I make my new object called value, I'm expecting my key name to be the same as the one in the current loop; However, I'm getting just getting back key whereas if I just console log it out it is the key name I wanted. What is going on here? I'm sure there's a reason behind this that I haven't heard of yet.

const testObj = (something => {
  for (let key in something) {
    let value = {key: something[key]};
    console.log(key);
    console.log(value);
  }
})

let test = {'name': 'yomam', 'address': 'camelbak'};
console.log(testObj(test));
/*
name
{ key: 'yomam' }
address
{ key: 'camelbak' }
*/

1 Answers1

1

let value = {[key]: something[key]};

This will set the key of the object to the key of the loop

Ahmad Suddle
  • 190
  • 7