Reputation: 429
I am trying to destructure a nested object, I can do something like below to get calories and carbohydrates
const { calories } = action.payload
const { quantity: carbohydrates } = action.payload.totalNutrients.CHOCDF
from the object whose picture I have below
but to get my other items such as fat, protein, fiber, etc... Would I just continue to do it the way I am doing it or is there an easier way to restructure multiple needed items?
Just for clarification, I am just trying to do this a better way:
const { calories } = action.payload
const { quantity: carbohydrates } = action.payload.totalNutrients.CHOCDF
const { quantity: fat } = action.payload.totalNutrients.FAT
const { quantity: fiber } = action.payload.totalNutrients.FIBTG
const { quantity: protein } = action.payload.totalNutrients.PROCNT
Upvotes: 1
Views: 163
Reputation: 20821
It is possible to destructure (while assigning to new variable names) everything all at once like this:
// approximation of the data you are working with
const action = {
payload: {
calories: 55,
totalNutrients: {
CHOCDF: {
quantity: 8.52
},
CHOLE: {
quantity: 0
}
}
}
};
const {
calories,
totalNutrients: {
CHOCDF: {
quantity: carbohydratesQuantity
},
CHOLE: {
quantity: cholesterolQuantity
}
}
} = action.payload;
console.log({
calories,
carbohydratesQuantity,
cholesterolQuantity
});
If you want the whole object instead of just their quantity property, you could do:
const action = {
payload: {
calories: 55,
totalNutrients: {
CHOCDF: {
quantity: 8.52,
label: "Carbs",
unit: "g"
},
CHOLE: {
quantity: 0,
label: "Cholesterol",
unit: "mg"
}
}
}
};
const {
calories,
totalNutrients: {
CHOCDF: carbohydrates,
CHOLE: cholesterol
}
} = action.payload;
console.log({
calories,
carbohydrates,
cholesterol
});
const action = {
payload: {
calories: 55,
totalNutrients: {
CHOCDF: {
quantity: 8.52,
label: "Carbs",
unit: "g"
},
CHOLE: {
quantity: 0,
label: "Cholesterol",
unit: "mg"
},
FAT: {
quantity: 10,
label: "Fat",
unit: "g"
},
FIBTG: {
quantity: 0.348,
label: "Fiber",
unit: "g"
},
PROCNT: {
quantity: 0.6,
label: "Protein",
unit: "g"
}
}
}
};
const {
calories,
totalNutrients: {
CHOCDF: {
quantity: carbohydrates
},
CHOLE: {
quantity: cholesterol
},
FAT: {
quantity: fat
},
FIBTG: {
quantity: fiber
},
PROCNT: {
quantity: protein
}
}
} = action.payload;
console.log({
calories,
carbohydrates,
cholesterol,
fat,
fiber,
protein
});
There are some good examples here at MDNs page on Destructuring_assignment under Object destructuring. I recommend that you spend some time reading through this page.
Here's a codepen example for you to fork and experiment with.
Upvotes: 3