0

So, I want to have an object with dynamic property names, retrieving from an array. This is what I've tried so far:

var fruits = {};

var props = ['orange', 'apple', 'banana'];

for (var i = 0; i < props.length; i++) {
  fruits.props[i] = 'Juice';
}

My object should look like this:

fruits { orange: 'Juice', apple: 'Juice', banana: 'Juice' };

But I'm getting the error:

Uncaught TypeError: Cannot set property '0' of undefined(…)

What am I doing wrong?

Edit:

Not because the question title is similar, the question itself has to be as well. This question is different from 695050 because I'm not retrieving my property names from the DOM. I'm trying to loop an array and it tends to cause a confusion when working with the brackets notation.

Community
  • 1
  • 1
Anna
  • 469
  • 1
  • 6
  • 20

3 Answers3

4

In your code fruits.props[i] = 'Juice'; would try to set the 0th index value of props property where the property is undefined and causing the error.

Use bracket notation for assigning object property using a string.

var fruits = {};

var props = ['orange', 'apple', 'banana'];

for (var i = 0; i < props.length; i++) {
  fruits[props[i]] = 'Juice';
  //----^^^^^^^^^^-----
}

console.log(fruits);
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
3

fruits.props[i] = 'Juice';

Needs to be: fruits[props[i]] = 'Juice';

Because using dot notation, you cannot use a dynamic property name, but with bracket notation, the property is expected to be a string and that string can be a literal or a dynamically gotten value.

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
3

You need the key in brackets, read more about property accessors.

Property accessors provide access to an object's properties by using the dot notation or the bracket notation.

Syntax

object.property
object["property"]

var fruits = {};

var props = ['orange', 'apple', 'banana'];

for (var i = 0; i < props.length; i++) {
    fruits[props[i]] = 'Juice';
    //    ^        ^
}

console.log(fruits);
Community
  • 1
  • 1
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392