替换和计算数组中的值

时间:2014-08-17 17:54:55

标签: javascript angularjs

我有一系列项目是ids

 var names = ['1','2', '1', '3'];

然后使用此id我发出一个ajax请求,期望接收每个id的名称并用它替换它;

 var names = ['ham','cheese', 'ham', 'onion'];

最后显示如下列表:

 ham x2, cheese, onion

问题是我得到了这个:

 ham x2, cheese, ham, onion

我该怎么做?

这是我的代码

var list = [];

function _checkIngredients(pizza, ingredient) {
    for (var i = 0; i < list[pizza].ingredients.length; ++i) {
        if (list[pizza].ingredients[i] == ingredient) {
            return true;
        }
    }
    return null;
}

pizzas.get().then(function (response) {
    list = response.data;
    angular.forEach(list, function (v, k) {
        //Find ingredients names per pizza
        angular.forEach(v.ingredients, function (i, ik) {
            ingPerPizza.get(i).then(function (response) {
                var name = response.data.name;
                if ( _checkIngredients(k, name) ) {
                    list[k].ingredients[ik] = '2x' + name;
                } else {
                    list[k].ingredients[ik] = name;
                }
            });
        });
    });

谢谢!

3 个答案:

答案 0 :(得分:1)

您可以将所有成分存储在数组中,然后使用underscore'shttp://underscorejs.org/#_.groupBy函数按名称对其进行分组。

pizzas.get().then(function (response) {
    list = response.data;
    angular.forEach(list, function (v, k) {
        //Find ingredients names per pizza

        var ingredients = [];
        angular.forEach(v.ingredients, function (i, ik) {
            ingPerPizza.get(i).then(function (response) {
                ingredients.push({name: response});
            }
        }
        ingredients = _.groupBy(ingredients,'name');
        //do something what you want with this object and attach to pizza       
    });
});

现在你会得到类似的东西:

{
  "ham": [
    {
      "name": "ham"
    },
    {
      "name": "ham"
    }
  ],
  "cheese": [
    {
      "name": "cheese"
    }
  ],
  "onion": [
    {
      "name": "onion"
    }
  ]

因此,您可以使用ingredients['cheese'].length轻松检查每个ingriendt的数量。

您还可以使用以下内容显示它们:

<div ng-repeat="(key,data) in ingredients">{{key}} x {{data.length}}</div>

http://jsfiddle.net/aartek/7gfs27zz/

答案 1 :(得分:1)

您可以扩展Array和Object natives以提供此功能。这将返回:[“ham:2”,“cheese:1”,“onion:1”]。

     var names = ['ham','cheese', 'ham', 'onion'];

     Array.prototype.compileObj = function() {

        var instances = {};

        this.forEach( function( element, index ) { 

            if ( instances[element]) {
                instances[element]+= 1
            }

            else { 
                instances[element] = 1;
            }


        });

        return instances
    }

    Object.prototype.toArr = function() {

        var returnArr = [],
            obj = this;

        Object.keys( obj ).forEach( function( element, index) {

            returnArr.push( element + ': ' + obj[element] );

        });

        return returnArr;
    }

    console.log( names.compileObj().toArr() )

答案 2 :(得分:1)

我会使用像lodash或下划线这样的外部库,在这种情况下,countBy函数可以正常工作:

var list = ['ham','cheese', 'ham', 'onion'];
$scope.result = _.countBy( list );

结果将是:

{
  "ham": 2,
  "cheese": 1,
  "onion": 1
}

然后打印出来:

<div ng-repeat="(key,data) in result">{{key}} x{{data}}</div>