在javascript中将数组添加到特定位置(基于键值)的数组中

时间:2015-06-10 09:19:05

标签: javascript arrays angularjs multidimensional-array

我搜索了很多,但我无法在网上得到满意的答案。在javascript中,如何根据键值将数组添加到特定位置的另一个多维数组?

finalArray = []; //final result to be stored here
for(var i=0; i<5; ++i)
{
    var temp = [];
    for(var j in $scope.team[i])
    {
        // counter = some value calculated here
        temp[j] = $scope.team[i][j][counter];
    }
    finalArray[group[i]] = temp; // This gives an error
}
基本上,我有

group = [ 'alpha' ,'beta', 'gamma' ]; //this array generated dynamically

我的finalArray应该是,

finalArray['alpha'] = [ some records ];
finalArray['beta'] = [ some records ];
....

据我所知,将数组添加到另一个数组的方法是使用.push()方法,但是创建索引为0,1,2 ......这是不希望的。请帮帮我

3 个答案:

答案 0 :(得分:1)

您必须将finalArray变量定义为Object而不是Array:

var finalArray = {}; //or better in your case finalMap

答案 1 :(得分:1)

var group = [ 'alpha' ,'beta', 'gamma' ];
var finalArray = {}; //declare it object as you dont want 0,1 indexes
for (var index in group){
    finalArray[group[index]] = "some records/arry of records"
}
console.log(finalArray);  

DEMO

答案 2 :(得分:1)

您必须使用Object而不是Array。在代码中进行以下更改

finalArray = {}; //final result to be stored here
for(var i=0; i<5; ++i)
{
    var temp = {};
    for(var j in $scope.team[i])
    {
        // counter = some value calculated here
        temp[j] = $scope.team[i][j][counter];
    }
    finalArray[group[i]] = temp;
}
console.log(finalArray); //to see the object key value structure

现在您可以使用group [i] name引用finalArray中的值。希望这有帮助