Reputation: 1
Hi and just what the question suggests, I need help with my code to increment through an object in an object so that I can use it for a "your cart" feature in an ecommerce website for my project. Here is the code:
var products = {
product1: {
name: "Balenciaga Black Shoes",
quantity: 2,
price: 50,
size: "L",
shipping: 20
},
product2: {
name: "Gucci Pink Bag",
quantity: 1,
price: 70,
size: "Big",
shipping: 20
}
};
function myFunc() {
for (const key in products) {
for (const key2 in key) {
console.log(`${key2}: ${key[key2]}`);
}
}
}
myFunc()
Upvotes: 0
Views: 29
Reputation: 425
Why don't you store your products in an array instead of an object ? Anyway, you need here to loop through all the values of your products
object then need to loop through all the keys of this product :
var products = {
product1: {
name: 'Balenciaga Black Shoes',
quantity: 2,
price: 50,
size: 'L',
shipping: 20,
},
product2: {
name: 'Gucci Pink Bag',
quantity: 1,
price: 70,
size: 'Big',
shipping: 20,
},
};
for (const product of Object.values(products)) {
for (const key in product) {
console.log(`${key}: ${product[key]}`);
}
}
Upvotes: 0
Reputation: 218960
Here you're iterating over the key name itself, which is just a string:
for (const key2 in key) {
Instead, iterate over the property named by that key:
for (const key2 in products[key]) {
Similarly, reference that property when outputting:
console.log(`${key2}: ${products[key][key2]}`);
You likely also want to output the hierarchy of properties so you know which object had which property value:
console.log(`${key}:${key2}: ${products[key][key2]}`);
For example:
var products =
{
product1: {
name: "Balenciaga Black Shoes",
quantity: 2,
price: 50,
size: "L",
shipping: 20
},
product2: {
name: "Gucci Pink Bag",
quantity: 1,
price: 70,
size: "Big",
shipping: 20
}
};
function myFunc() {
for (const key in products) {
for (const key2 in products[key]) {
console.log(`${key}:${key2}: ${products[key][key2]}`);
}
}
}
myFunc();
Upvotes: 2