[英]Remove deep items from an object
I'm looking to remove the encapsulating object that recipeStep
resides in that's equal to heat
.我希望删除
recipeStep
所在的封装对象,它等于heat
。 So the first array items in recipeMealSteps
would be removed as it contains heat
.因此,
recipeMealSteps
的第一个数组项将被删除,因为它包含heat
。
I've tried using .map
and .filter
, but I'm not getting back the whole object minus the heat
steps.我试过使用
.map
和.filter
,但我没有取回整个对象减去heat
步骤。
Here's what I've got so far that's failing:这是我到目前为止失败的内容:
let filteredRecipes = meals.map((m) =>
m.mealTypeRecipes.map((r) => r.recipeMealSteps.filter((s) => s.recipeStep !== 'heat'))
);
let meals = [
{
mealId: 0,
mealDescription: "Favourties",
mealTypeRecipes: [
{
recipeAuthor: "Frank Doe",
recipeDescription: "Great chicken dish for those that don't eat chicken",
recipeID: 0,
recipeMealSteps: [
{
recipeDesc: "Heat up the oven",
recipeStep: "heat",
},
{
recipeDesc: "Allow it to cook",
recipeStep: "cool",
},
{
recipeDesc: "Take it out the oven",
recipeStep: "out",
},
],
},
{
recipeID: 1,
recipeName: "Fish Dish",
recipeMealSteps: [
{
recipeDesc: "Heat up the oven",
recipeStep: "heat",
},
{
recipeDesc: "Allow it to cook",
recipeStep: "cool",
},
{
recipeDesc: "Take it out the oven",
recipeStep: "out",
},
],
},
],
},
];
let filteredRecipes = meals.map(({mealTypeRecipes, ...m}) => ({
...m,
mealTypeRecipes: mealTypeRecipes.map(({recipeMealSteps,...r}) => ({
...r,
recipeMealSteps: recipeMealSteps.filter((s) => s.recipeStep !== 'heat')
})
)}));
EDIT:编辑:
Explanation: in the first map, we get as a parameter of the callback function every meal item.说明:在第一个地图中,我们获取每个餐点作为回调函数的参数。 We deconstruct it so that 'm' is an object with all properties 'mealTypeRecipes' (in this case, m has properties 'meadId' and 'mealDescription').
我们解构它,以便“m”是一个具有所有属性“mealTypeRecipes”的对象(在这种情况下,m 具有属性“meadId”和“mealDescription”)。 On the other hand we put in the variable 'mealTypeRecipes' the value of the property 'mealTypeRecipes'.
另一方面,我们将属性“mealTypeRecipes”的值放入变量“mealTypeRecipes”中。 This is done thanks to the spread operator "...".
这要归功于扩展运算符“...”。 This would be equivalent
这将是等效的
let filteredRecipes = meals.map((mealItem) => {
const {mealTypeRecipes, ...m} = mealItem
Then we return the reconstructed object returning the new value for property "mealTypeRecipes" and putting it together we the part of the object we didn't modify, "...m".然后我们返回重建的对象,返回属性“mealTypeRecipes”的新值,并将它与我们没有修改的对象部分“...m”放在一起。 This creates a copy of the old object, ensuring immutability.
这会创建旧对象的副本,确保不变性。
A more verbose way to do the same would be like this一个更详细的方法来做同样的事情是这样的
let filteredRecipes = meals.map((meal) => {
const {mealTypeRecipes, ...m} = meal;
return {
...m,
mealTypeRecipes: mealTypeRecipes.map((mealTypeRecipeItem) => {
const {recipeMealSteps,...r} = mealTypeRecipeItem;
return {
...r,
recipeMealSteps: recipeMealSteps.filter((s) => s.recipeStep !== 'heat')
}
})
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.