我正在尝试破坏嵌套对象,我可以做下面的事情来获取卡路里和碳水化合物
const { calories } = action.payload
const { quantity: carbohydrates } = action.payload.totalNutrients.CHOCDF
从我下面具有其图片的对象开始
但是要获取我的其他物品,例如脂肪,蛋白质,纤维等...我会继续按照我的方式进行操作吗,还是有一种更简单的方法来重组多个所需的项目?
为澄清起见,我只是想做一个更好的方法:
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
答案 0 :(得分:3)
可以像这样一次分解所有内容(同时分配给新的变量名称):
// 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
});
如果您想要整个对象而不只是它们的数量属性,可以执行以下操作:
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
});
Destructuring_assignment under Object destructuring的MDN页面上有一些很好的示例。我建议您花一些时间阅读此页面。
这是codepen example,供您分叉并进行实验。