1

I am trying to generate an object via a for loop, the problem I am having is that the property name is not being generated instead it is just inserted as the variable name.

Here is an example:

for (let key in person) { 
    let obj = {key : person[key] };
    console.log(obj);
}

If you run this it prints

{ key : "smith" }

The desired object would be

{ name : "smith" }

any ideas on how to achieve this? thank you in advanced.

rvncpn
  • 75
  • 5

3 Answers3

2

What you want is :

const person = {
  age: 18,
  size: '1m74',
  eyeColor: 'blue',
};

for (let key in person) { 
  const obj = { 
    [key] : person[key],
  };

  console.log(obj);
}

Look at here for explainations



Example with Array.forEach and Object.keys

const person = {
  age: 18,
  size: '1m74',
  eyeColor: 'blue',
};

Object.keys(person).forEach((x) => {
  const obj = {
    [x]: person[x],
  };

  console.log(obj);
});
Orelsanpls
  • 22,456
  • 6
  • 42
  • 69
1

You can achieve using

for (let key in person) { 
  const obj = {};
  obj[key] = person[key];

  console.log(obj);
}
Birbal Singh
  • 1,062
  • 7
  • 16
0

You can do this by :

obj = {name: person[key] }
Sagar Jajoriya
  • 2,377
  • 1
  • 9
  • 17
  • i will not always be sure off all the properties in the object so hard coding is not an option i am afraid! – rvncpn Mar 19 '18 at 16:41