JavaScript - 构建复杂数据的对象

时间:2015-11-12 07:02:19

标签: javascript angularjs

我正在编写一个从表中“记忆数据”的函数。函数签名(在AngularJS中)是

$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 个答案:

答案 0 :(得分: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;
    }
}