AngularJS:检查对象中是否存在键/值并构造对象数组

时间:2014-09-30 15:24:30

标签: javascript arrays angularjs

这是我正在使用的服务方法。它从项目中找到所有收入(与此问题相关:Angular service calling another service)并创建一个新的对象数组。

我希望这个对象数组按年和三个月对收入进行排序,因此我可以在视图中轻松地循环(使用ng-repeat)。

我当前的数据(由Incomes.buildAndGetIncomes()返回,您可以在下面看到):

[  


 {  
      "projectName":"Deuxième test",
      "clientName":"Deuxième client",
      "typeIncome":"Accompte",
      "amount":1000,
      "date":"2014-09-10",
      "notes":"Chèque / LDD",
      "trim":"third",
      "year":"2014"
   },
   {  
      "projectName":"efzefze",
      "clientName":"zfezefzef",
      "typeIncome":"Accompte",
      "amount":30,
      "date":"2014-09-10",
      "notes":"fzefzef",
      "trim":"third",
      "year":"2014"
   },
   {  
      "projectName":"Nouveau test",
      "clientName":"Nouveau client",
      "typeIncome":"Accompte",
      "amount":16,
      "date":"2014-09-19",
      "notes":"CC",
      "trim":"third",
      "year":"2014"
   },
   {  
      "projectName":"Nouveau projet",
      "clientName":"Nouveau client",
      "typeIncome":"Accompte",
      "amount":1200,
      "date":"2014-05-17",
      "notes":"Chèque cc",
      "trim":"second",
      "year":"2014"
   },
   {  
      "projectName":"Projet test",
      "clientName":"Client test",
      "typeIncome":"Accompte",
      "amount":1500,
      "date":"2014-01-15",
      "notes":"Chèque cc",
      "trim":"first",
      "year":"2014"
   },
   {  
      "projectName":"Deuxième test",
      "clientName":"Deuxième client",
      "typeIncome":"Reliquat",
      "amount":4500,
      "date":"2014-09-27",
      "notes":"Virement",
      "trim":"third",
      "year":"2014"
   },
   {  
      "projectName":"efzefze",
      "clientName":"zfezefzef",
      "typeIncome":"Reliquat",
      "amount":8,
      "date":"2014-09-05",
      "notes":"zefzefzef",
      "trim":"third",
      "year":"2014"
   },
   {  
      "projectName":"Nouveau test",
      "clientName":"Nouveau client",
      "typeIncome":"Reliquat",
      "amount":7,
      "date":"2014-09-27",
      "notes":"LDD",
      "trim":"third",
      "year":"2014"
   }
]

我想要的数据结构:

[
    {
        year: 2014,
        trim: [
            {
                name : 'first',
                content : [
                    // some content
                ]

            },
            {
                name : 'second',
                content : [
                    // some content
                ]

            }
        ]


    },
    {
        year: 2013,
        trim: [
            {
                name : 'first',
                content : [
                    // some content
                ]

            }
        ]


    }

]

以下是我现在正在使用的方法:

self.trimestral = function(){
  var deferred = $q.defer();
  self.buildAndGetIncomes().then(function(result) {
    var trimestral = [];
    var incomes = result;


    angular.forEach(incomes, function(income, i){
      var year = income.year,
          trim = income.trim,
          newTrim = {},
          newTrimContent = {};

      if( i === 0 ){
          newTrim.year = year;
          newTrim.trim = [];
          newTrimContent ={};
          newTrimContent.name = trim;
          newTrimContent.content = [];
          newTrimContent.content.push(income);

          trimestral.push(newTrim);
          console.log(trimestral);
          trimestral[0].trim.push(newTrimContent);
      }
      else {
        var maxLength = incomes.length;
        for (var h = 0; h<maxLength; h++){
            if(trimestral[h].year === year){



                for (var j = 0; j<trimestral[h].trim.length; j++){
                  console.log(h,j,trimestral[h].trim[j].name === trim);
                  if(trimestral[h].trim[j].name === trim){ // trimester already exists

                    trimestral[h].trim[j].content.push(income);
                  }
                  else {// trimester doesn't exist, create it
                    var createTrim = {};

                    createTrim.name = trim;
                    createTrim.content = [];
                    createTrim.content.push(income);
                    trimestral[h].trim.push(newTrimContent);
                  }
                }




            }
            else {
             newTrim.year = year;
              newTrim.trim = [];
              newTrimContent ={};
              newTrimContent.name = trim;
              newTrimContent.content = [];
              newTrimContent.content.push(income);

              trimestral.push(newTrim);
              console.log(trimestral);
              trimestral[0].trim.push(newTrimContent);
            }

        }

      }

    });

   deferred.resolve(trimestral);      
  });
return deferred.promise;    
};

这段代码按照假设运行,它检查我们是否在循环的第一个索引上,并且它推动了那个三个月的年/三个月/内容。那个结构还可以。

现在我的问题是我需要检查年份是否已经存在,然后检查该年份对象中是否存在三个月,构建像我粘贴在上面的对象数组。 < / p>

我尝试了很多方法,但对我的JS技能来说似乎太难了......有什么帮助吗?

2 个答案:

答案 0 :(得分:1)

这肯定可以使用几个循环,但代码将很难遵循。如果您可以引入另一个库,请考虑使用underscore.js。有了它,你可以做这样的事情......

var trimestral = _(incomes).chain()
    .groupBy('year')
    .map(function (items, year) {
        return {
            year: year,
            trim: _(items).chain()
                    .groupBy('trim')
                    .map(function(content, trimester) {
                        return {
                            trim: trimester,
                            content: content
                        };
                    })
                    .sortBy(function(i) { 
                        var trimesters = {
                            first: 1,
                            second: 2,
                            third: 3
                        };
                        return trimesters[i.trim];
                    }).value()
        };
    })
    .sortBy('year')
    .value();

Live Demo

答案 1 :(得分:0)

我终于要求一位优秀的网络开发人员帮我解决这个问题。他告诉我在两个步骤中执行此操作:构造对象,然后按照我需要的方式格式化

所以我这样做了:

self.trimestral = function(){
  var deferred = $q.defer();
  var global = [];
  self.buildAndGetIncomes().then(function(result) {
    var trimestral = {};

    var incomes = result;

    // First loop, construct the object
    angular.forEach(incomes, function(income, i){
      var year = income.year,
          trim = income.trim,
          newTrim = {},
          newTrimContent = {};          
          if(trimestral[year] === undefined){
            trimestral['year' , year] = {};

          }
          if(trimestral[year][trim] === undefined) {
            trimestral[year][trim] = [];               
          }
           trimestral[year][trim].push(income);        

    });

   deferred.resolve(global);

   // Second loop, format the data
    for ( prop in trimestral ) {          
      newYear = {};
      newYear.name = prop;
      newYear.content = [];          
      for ( trim in trimestral[prop]){
        newTrim = {};
        newTrim.name = trim;
        newTrim.content = [];           
        newTrim.content = trimestral[prop][trim];              
        newYear.content.push(newTrim);
      }
      global.push(newYear);
    }         
  });
return deferred.promise;    
};

我想它可能更干净,但它有效并且比我预期的要简单得多。

相关问题