How to display the sum of an X value where it has the same name?

2

Hello, let's say 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 angle, I wanted to display in the html thus, adding the "qtd" and holding only a name the same way below.

    Coisa A possui 5
    Coisa B possui 12
    
asked by anonymous 25.07.2016 / 15:03

2 answers

4

Use the reduce() native function to perform summing by 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
}
    
25.07.2016 / 16:05
1

I do not quite understand what you want, but to make a simple list from JSON , just do ng-repeat with 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 the 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 working example in JSFiddle.

    
25.07.2016 / 15:35