如何在同一个数组元素中放入相同的值

时间:2017-01-20 11:33:01

标签: javascript arrays json node.js

我在js工作,我得到了一个我的阵列的响应如下:

我拥有的数组结构:

 [ 
  { test_name: 'comp 1 test 1',
    program_id: 1,
  },
  { test_name: 'comp 1 test 2',
    program_id: 1,
  },
  { test_name: 'complete 2 test 1',

    program_id: 2,
   } 
]

但我希望得到它:

 [ 
  [
  { test_name: 'comp 1 test 1',
    program_id: 1,
  },
  { test_name: 'comp 1 test 2',
    program_id: 1,
  }
  ],
  [
   { test_name: 'complete 2 test 1',

    program_id: 2,
   } 
  ]
]

我使用Promises从数据库获取数据

 var req1 = new Promise(function(resolve, reject) { 
    db1.serialize(function() {

        var exer_names = [];
        var prog_status = 1;
        db1.each("SELECT  prog_name, prog_status,id  from programs Where prog_createdby = "+userId+" and prog_orgid = "+prog_orgid+" and prog_status = "+prog_status, function(err, row) {

        exer_names.push({id : row.id, prog_name: row.prog_name});

        },function(){

            resolve(exer_names);

        });
    });
});

var req2 = new Promise(function(resolve, reject) { 
    db1.serialize(function() {

        var test_names = [];

        db1.each("SELECT * from tests Where test_createdby = "+userId+" and org_id = "+prog_orgid+"", function(err, row) {

            test_names.push({test_name: row.test_name,test_alias: row.test_alias,test_createdby: row.test_createdby,sequences: row.sequences, duration: row.duration, program_id: row.prog_id, id: row.id });

        },function(){

             resolve(test_names);

        });

    });
});

  Promise.all([req1,req2]).then(function(programs, progerror) {
    programs[0].forEach(function(program){
    // what should be there??
    });

  }).catch(function(err) {

    console.log('Catch: ', err);

});

2 个答案:

答案 0 :(得分:3)

您可以在program_id的基础上创建数组,然后将这些数组推送到父数组

var parent = [];
var child = [];
var another_child = [];
parent.push(child);
parent.push(another_child);

答案 1 :(得分:1)

您可以创建一个由program_id索引的2D数组,并使用2个嵌套循环

正确填充它



var input =  [
      {
        test_name: 'comp 1 test 1',
        program_id: 1,
      },
      {
        test_name: 'comp 1 test 2',
        program_id: 1,
      },
      {
        test_name: 'complete 2 test 1',
        program_id: 2,
      }
    ];
    output = input.map(x => x.program_id).filter((x,i,arr) => arr.indexOf(x) === i).map(x => [x]);
    output.forEach((x,i,arr) => {
      input.forEach(y => {
        if (y.program_id === x[0]) x.push(y);
      })
    });
    output = output.map(x => x.slice(1));
    console.log(output);