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

AngularJS : check if key/value exist in object and construct an array of objects

本文关键字:数组 一个对象 检查 对象 存在 是否 AngularJS      更新时间:2023-09-26

下面是我正在使用的一个服务的方法。它查找来自项目的所有收入(与这个问题相关:Angular服务调用另一个服务),并生成一个新的对象数组。

我希望这一系列对象按年份和妊娠期对收入进行排序,这样我就可以很容易地在视图中循环(重复ng)

我的当前数据(由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;    
};

这个代码按预期工作,它检查我们是否在循环的第一个索引上,并推送该三个月的年份/三个月/内容。这种结构还可以。

现在我的问题是,我需要检查年份是否已经存在,然后,检查年份对象中是否存在妊娠期,构建一个对象数组,就像我粘贴在上面一样

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

这当然可以使用几个循环,但代码很难理解。如果你可以引入另一个库,可以考虑undercore.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();

实时演示

我终于请了一位优秀的web开发人员朋友来帮助我。他告诉我在中执行两个步骤构造对象,然后按照我需要的方式对其进行格式化

所以我做了这个:

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;    
};

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