【问题标题】:Object.assign for an array of objectsObject.assign 用于对象数组
【发布时间】: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


【解决方案1】:

[更正x2] 也许是这样的:

copy = ingredients.map(o=>Object.assign({},o))

【讨论】:

  • 该死,我复制了错误的行。这里是:copy = [...ingredients.map(o=>Object.assign({},o))]
  • 扩展语法不会产生太大影响,因为map() 无论如何都会返回一个新数组
猜你喜欢
  • 2019-04-22
  • 2020-05-01
  • 2017-03-01
  • 2016-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-31
相关资源
最近更新 更多