How to display the sum of an X value where you have the same name?

Asked

Viewed 57 times

2

Hello, let’s assume I have an object that has the following values

    var json = [
    {"nome":"Coisa A", qtd:2},
    {"nome":"Coisa A", qtd:3},
    {"nome":"Coisa B", qtd:5},
    {"nome":"Coisa B", qtd:7}
    ]

Well, I can return these values to display in a list with the angular, I wanted to display in html like this, adding the "Qtd" and keeping only one name as below.

    Coisa A possui 5
    Coisa B possui 12
  • 1

    Do you have control over the generation of this json? Ideally it will already come ready to display, although it is not difficult to do in js.

  • Yes, but I’m using the same bind for two places on the page so I can’t already bring with this filter. I have to apply only when displaying to a list in html

2 answers

4


Use the native function reduce() to perform sum per grouping. Example below:

var json = [
  {"nome":"Coisa A", qtd:2},
  {"nome":"Coisa A", qtd:3},
  {"nome":"Coisa B", qtd:5},
  {"nome":"Coisa B", qtd:7}
];

var result = json.reduce(function(res, obj) {

  if (res._array.indexOf(obj.nome) === -1) {  
    res._array.push(obj.nome);
    res[obj.nome] = obj.qtd;
  }
  else {
    res[obj.nome] += obj.qtd;
  }

  return res;

}, {_array:[]});

console.log(result);

Your result will be:

{
  "_array": [
    "Coisa A",
    "Coisa B"
  ],
  "Coisa A": 5,
  "Coisa B": 12
}

1

I don’t quite understand what you want, but to make a simple list from a JSON, just do the ng-repeat with the JSON.

An example would be:

<div ng-controller="MyCtrl">
    <ul>
        <li ng-repeat="var in items">{{var.nome}} possui {{var.qtd}}</li>
    </ul>
</div>

And in Angular, just do the following:

var myApp = angular.module('myApp', []);

function MyCtrl($scope) {
    $scope.items = [{
        nome: "Coisa A",
        qtd: "2"
    }, {
         nome: "Coisa B",
         qtd: "3"
    }, {
         nome: "Coisa C",
         qtd: "7"
    }];
}

The result will be:

Coisa A possui 2
Coisa B possui 3
Coisa C possui 7

See a functional example in Jsfiddle.

  • Almost expensive my problem is not to exhibit this way, but it is the following see that I have two "THINGS A" and two "THINGS B", and each of them has a different amount I want to add the amounts and keep only one name.

Browser other questions tagged

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