0

So I'm able to use object.assign on an object like this

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); 

but i'm having trouble doing this with a list of objects like this:

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

From what I've been reading, it looks like the array.map method would probably be the best way, but I'm having some issues getting it right.

Based on this I tried something like this: this.editableIngredients = ingredients.flat().map(p => Object.assign(p));

Have also tried a few different iterations based on reading this

12
  • 1
    Object.assign({}, ...ingredients)? actually, no, since each ingredient has the same keys, you'll need to do something about that Commented Apr 23, 2020 at 3:25
  • 1
    @JaromandaX don't think that's going to work. You'd end up with only the last of each property. Edit: you noticed 😉 Commented Apr 23, 2020 at 3:26
  • 1
    this.editableIngredients = ingredients.map(p => Object.assign({}, p)); ? Commented Apr 23, 2020 at 3:28
  • 3
    I guess the question is, what is the expected result Commented Apr 23, 2020 at 3:28
  • 2
    I think @Kosh has it but I'd still use the spread syntax, ie ingredients.map(i => ({...i})) Commented Apr 23, 2020 at 3:29

1 Answer 1

1

[CORRECTEDx2] Maybe something like this:

copy = ingredients.map(o=>Object.assign({},o))
Sign up to request clarification or add additional context in comments.

2 Comments

Dammit, I copied the wrong line. Here it is: copy = [...ingredients.map(o=>Object.assign({},o))]
The spread syntax isn't going to make much of a difference since map() will return a new array anyway

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.