【发布时间】:2020-04-23 03:20:52
【问题描述】:
所以我可以在这样的对象上使用 object.assign
let recipe = {"recipeId":1,"title":"Instant Pot® Chicken and Wild Rice Soup","directions":"Lorem ipsum dolor sit","imageLink":"https://images-gmi-pmc.edge-generalmills.com/60c3ebda-50a7-415e-8c66-14f6c9b93034.jpg","id":"1"}
this.editableRecipe = Object.assign({},recipe);
但是我在使用这样的对象列表时遇到了麻烦:
let ingredients = [
{"ingredientId":1,"amount":1,"unit":"package","ingredient":"(20 oz) boneless skinless chicken thighs","note":"patted dry","id":"1"},
{"ingredientId":2,"amount":1,"unit":"teaspoon","ingredient":"salt22323","note":"","id":"2"},
{"ingredientId":3,"amount":0.5,"unit":"teaspoon","ingredient":"pepper","note":"","id":"3"},
{"ingredientId":4,"amount":2,"unit":"tablespoons","ingredient":"butter","note":"","id":"4"},
{"ingredientId":5,"amount":1,"unit":"package","ingredient":"(20 oz) boneless skinless chicken thighs","note":"patted dry","id":"5"},
{"ingredientId":6,"amount":1,"unit":"teaspoon","ingredient":"salt","note":"","id":"6"}
];
// this.editableIngredients = something for object assign for the array here
从我一直在阅读的内容来看,array.map 方法可能是最好的方法,但我在正确处理时遇到了一些问题。
基于this 我尝试了这样的事情:this.editableIngredients = ingredients.flat().map(p => Object.assign(p));
还根据阅读 this 尝试了一些不同的迭代
【问题讨论】:
-
Object.assign({}, ...ingredients)?实际上,不,因为每种成分都有相同的键,所以你需要做一些事情 -
@JaromandaX 认为这行不通。你最终只会得到每个属性的最后一个。 编辑:你注意到了吗????
-
this.editableIngredients = ingredients.map(p => Object.assign({}, p));? -
我想问题是,预期的结果是什么
-
我认为@Kosh 有,但我仍然会使用扩展语法,即
ingredients.map(i => ({...i}))
标签: javascript arrays object array-map