Marco Pereira
Marco Pereira

Reputation: 21

Cannot set to undefined value in ID

Hello for some reason is always giving me error when i try add the values in my foor loop, here is my funciton:

var productIds = [1,2,3,4,5];

var products = {};  
for (i = 0; i < productIds.length; ++i) {

    products[i]['id'] = id;
}

My error is:

ht TypeError: Cannot set property 'id' of undefined.

Upvotes: 1

Views: 81

Answers (4)

Ripon Uddin
Ripon Uddin

Reputation: 714

Try this

 var productIds = [1,2,3,4,5];
 var products = {};  
 for (i = 0; i < productIds.length; ++i) {
    products[i]={"id":productIds[i]};
 }

It should be work for you.
Note : products parameter data work as Object Data.

Upvotes: 0

palaѕн
palaѕн

Reputation: 73976

You can either set the products[i] to a new object inside the for loop first like:

products[i] = {};
products[i]['id'] = id;

Or, add the object inline like:

products[i]= { 'id': id };

Or, simply use Object property shorthand like:

products[i]= { id };

DEMO:

var productIds = [1, 2, 3, 4, 5];
var products = {}, id = 2;
for (i = 0; i < productIds.length; ++i) {
  products[i] = {id};
}
console.log(products);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 2

Abu Tahir
Abu Tahir

Reputation: 382

var productIds = [1,2,3,4,5];

var products = {};  

productIds.forEach(item => {
	var id_available = item in products
	if (!id_available) {
		products[item] = {id : item}
	} else {
		products[item].id = item
	}
})
console.log(products)

Hope this helps

Upvotes: 0

Sajeeb Ahamed
Sajeeb Ahamed

Reputation: 6418

Write your code by this approach-

var productIds = [1,2,3,4,5];

var products = {};  
for (i = 0; i < productIds.length; ++i) {
  products[i] = {};
  products[i]['id'] = productIds[i];
}

console.log(products);

Upvotes: 0

Related Questions