I’ve got this JSON response:
{id: 41071539879970,properties: {…},quantity: 1,variant_id: 41071539879970, key: '41071539879970:e0eefb458778bcb81e9efbf1fed9aa6b'}
final_price:1100
selling_plan_allocation:
{
price: 1100
selling_plan:
{
fixed_selling_plan:false
id:1079443490
name: "Delivery every 4 weeks”
}
}
And this is how I’m getting the response:
const subscriptionProducts = cartResponse.items.filter(item => item.selling_plan_allocation)[0];
However, I need to get the value of item.selling_plan_allocation.selling_plan.name
So I tried:
const subscriptionProducts = cartResponse.items.filter(item => item.selling_plan_allocation.selling_plan.name)[0];
which returned undefined. Then I tried:
const subscriptionProducts = cartResponse.items.filter(item => item.selling_plan_allocation)[0];
const subscriptionName = subscriptionProducts.selling_plan.name
Again this returned an error:
Uncaught (in promise) TypeError: Cannot read properties of undefined
(reading ‘name’)
Can somebody tell me what I’m doing wrong?
Don’t understand why this isn’t working.
>Solution :
To access the nested property safely, you need to ensure that all intermediate properties along the path are valid and not undefined. Here’s the correct way to access the name property within the nested structure:
const subscriptionProducts = cartResponse.items.find(item => item.selling_plan_allocation);
if (subscriptionProducts) {
const subscriptionName = subscriptionProducts.selling_plan_allocation.selling_plan.name;
console.log(subscriptionName);
} else {
console.log("No subscription products found");
}
In this code, the find function is used to locate the first item that has selling_plan_allocation. If such an item is found, you can safely access the nested properties, including selling_plan.name.