Agnes Agnes - 3 months ago 7
AngularJS Question

how to add an element of array to another object and count number

Firstly, I have an array with object element like below:

$scope.selectedIngredient = [object1, object2, object3, object1, object2];


secondly , I have a new object :

$scope.selectedIngredientResults = {};


Now I wanna achieve one function in javascript like this:

count each object element of array and put them into a new object and store each

count

$scope.selectedIngredientResults = [

{"object" : object1, "count" : 2},
{"object" : object2, "count" : 2},
{"object" : object3, "count" : 1}

];


here is array with object elements

[![here is new object result, this is what I want,

I was trying using

$scope.addIngredient = function(selectedElement) {

console.log('selectedElement', selectedElement);
$scope.selectedIngredient.push(selectedElement);
console.log('$scope.selectedIngredient' , $scope.selectedIngredient);
$scope.selectedIngredientResults = {};
var lengthofR = $scope.selectedIngredient.length;

for (var i = lengthofR - 1; i >= 0; i--) {
var selected = $scope.selectedIngredient[i]['ingredient_id'];
console.log('lengthofR', lengthofR);
if(selected){
if($scope.selectedIngredientResults.hasOwnProperty(selected)){

$scope.selectedIngredientResults[$scope.selectedIngredient]++;
}else {
$scope.selectedIngredientResults[$scope.selectedIngredient] = 1;
}
console.log('$scope.selectedIngredientResults', $scope.selectedIngredientResults );
}
}

}

Answer

first you need to apply group by by your key. then extract the result from the grouping. here is a transform function what you would need.

function transform(items) {
    items = items.reduce(function (memo, val) {
        var key = val['ingredient_id'];
        if (!memo[key]) {
            memo[key] = [];
        }
        memo[key].push(val);

        return memo;
    }, {});

    var result = [];
    for (var k in items) {
        var groups = items[k];
        result.push({ 'object': groups[0], 'count': groups.length });
    }

    return result;
}