Trolley with dynamic options with Angularjs

Asked

Viewed 583 times

0

Personal I have the following problem: how to subtract 2 arrays with Angularjs.

I’ve tried several ways and I couldn’t make that subtraction.

I am creating a product cart with dynamic optional in Angularjs

in that case the customer has made the following modification:

increment id 1004, 1000 decrease id 1001 added id 1002

original recipe:

[{"id":1004,"idproduto":3,"forma":"Alface","preco":1,"quantidade":1},{"id":1000,"idproduto":3,"forma":"Bacon","preco":2,"quantidade":1},{"id":1001,"idproduto":3,"forma":"Queijo Cheedar","preco":2,"quantidade":3}]

modified recipe:

[{"id":1004,"idproduto":3,"forma":"Alface","preco":1,"quantidade":2},{"id":1000,"idproduto":3,"forma":"Bacon","preco":2,"quantidade":2},{"id":1001,"idproduto":3,"forma":"Queijo Cheedar","preco":2,"quantidade":1},{"id":1002,"idproduto":2,"forma":"Bacon","preco":2,"quantidade":1}]

I need to reformulate this array because I need to show the changes in the shopping cart for the customer.

Product 500

+1 1004 (R$1,00)

+1 1000 (R$2,00)

+1 1002 (R$2,00)

-2 1001 (R$4,00)

Final recipe for the cart

[{"id":1004,"idproduto":3,"forma":"Alface","preco":1,"quantidade":1},{"id":1000,"idproduto":3,"forma":"Bacon","preco":2,"quantidade":1},{"id":1001,"idproduto":3,"forma":"Queijo Cheedar","preco":2,"quantidade":-2},{"id":1002,"idproduto":2,"forma":"Bacon","preco":2,"quantidade":1}]

And at the end would have to add the original array with the end to give low stock.

I’m correct in that logic?

1 answer

1


The name of this operation is diff, and you want to get the delta (difference) between the two collections.

There is a library calling for jsondiffpatch (link) that can be useful for you. The output is the delta (difference) between two sources.

The above example results in the following delta according to this library:

{
  "2": {
    "quantidade": [
      3,
      -2
    ]
  },
  "3": [
    {
      "id": 1002,
      "idproduto": 2,
      "forma": "Bacon",
      "preco": 2,
      "quantidade": 1
    }
  ],
  "_t": "a"
}
  • blz I will test, but anyway quarreled!

  • because it kind of didn’t work out the way I thought it would... test with the demo and it was the same example of yours... I’m missing a lot of data... the right way wouldn’t be the final recipe array not?

  • @Willian the purpose of the operation is to expose the difference; you can combine the result with your original array as you wish.

  • so I was able to implement now give me a hint on how to turn an array = that of the final recipe

  • Pow @Onosendai was thinking about this subject and that in the array[2] needed a reference to know which item is the modification... how would pull the rest of the items that are additional equal to bacon?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.