2015-11-12 70 views
0

我正在寫一個函數來從表中「記憶數據」。函數簽名(在AngularJS)是JavaScript - 構建複雜數據的對象

$scope.memoryTable = {}; 
$scope.memorize = function(name, category, value) { 
    if (typeof name !== 'undefined' && typeof category !== 'undefined' && typeof value !== 'undefined') { 

      // build data to $scope.memoryTable 

    } 
} 

memorise函數被調用每一個角度評估從表中的單元格數據的時間,並將該值添加到$scope.memoryTable

現在,我要實現的是建立一個數組按照此結構:

{ 
    "$name": { 
    "$category": "$value" 
    } 
} 

例如:

> memorize("David", "animal", "cat"); 
> memorize("David", "book", "fiction"); 
> memorize("Thomas", "animal", "dog"); 

將產生

console.log(JSON.stringify($scope.memoryTable)); 

{ 
    "David": { 
    "animal": "cat", 
    "book": "fiction" 
    }, 
    "Thomas": { 
    "animal": "dog", 
    } 
} 

我應該怎麼寫代碼來構建數據表?

回答

1

所以,你不使用數組,你實際上使用普通的舊JavaScript對象。

$scope.memoryTable = {}; 
$scope.memorize = function(name, category, value) { 
    if (typeof name !== 'undefined' && 
      typeof category !== 'undefined' && 
      typeof value !== 'undefined') { 
     // build data to $scope.memoryTable 
     // First, make sure there is an entry for name. 
     $scope.memoryTable[name] = $scope.memoryTable[name] || {}; 
     // Then, set the value for category under that name. 
     $scope.memoryTable[name][category] = value; 
    } 
}