0

Looking for a way to create a custom name on every iteration when creating a object. I put some code below and I can't figure out how to use a variable as a inner object name.

Thanks for your time!

var objects = {};
var name = [ "Olivia", "Oliver", "Amelia", "George", "Isla", "Harry", "Ava", "Noah", "Emily", "Jack", "Sophia", "Charlie", "Grace", "Leo", "Mia", "Jacob", "Poppy", "Freddie", "Ella"];

for (var x = 0; x < name.length; x++) {
  objects[x] = {name[x]: "etc"};
}

console.log(objects)
  • `{ [name[x]]: "etc" }` – ASDFGerte Feb 27 '20 at 21:14
  • 2
    Does this answer your question? [How to use a variable for a key in a JavaScript object literal?](https://stackoverflow.com/questions/2274242/how-to-use-a-variable-for-a-key-in-a-javascript-object-literal) – ASDFGerte Feb 27 '20 at 21:15
  • 1
    sidenote: the snippet will additionally produce unexpected results in global browser context, because your `name` collides with the predefined [`window.name`](https://developer.mozilla.org/en-US/docs/Web/API/Window/name), which autoconverts to string. – ASDFGerte Feb 27 '20 at 21:19
  • thanks @ASDFGerte that link was very helpful. This section specifically worked like a charm https://stackoverflow.com/questions/2274242/how-to-use-a-variable-for-a-key-in-a-javascript-object-literal/55602764#55602764 – Mr. Parrott Feb 27 '20 at 22:02
  • Also related: [MDN paragraph for computed property names](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names) – ASDFGerte Feb 27 '20 at 22:07
  • This is great insight @ASDFGerte, any suggestions on how to push these into the object? It keeps overwriting the object I created – Mr. Parrott Feb 28 '20 at 15:18

0 Answers0