Javascript 在 AngularJS 中创建映射 (Key,Value) 结构并填充来自 JSON 的数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37382662/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:15:38  来源:igfitidea点击:

Create map (Key,Value) structure in AngularJS and fill with data from JSON

javascriptangularjsdictionary

提问by kennechu

I have a list in AngularJS, $scope.list[];

我在 AngularJS 中有一个列表,$scope.list[];

What I want to know is how can I fill that list to fit a key,value structure like this:

我想知道的是如何填充该列表以适合这样的键值结构:

$scope.list[{key,value},{key,value}];

and I want to fill that "map" with data coming in json format:

我想用 json 格式的数据填充“地图”:

 {
  exportData {
    id: 1,
    name : "Peter",
    lastname : "Smith"
    age : 36
  }
}

Where the Idis going to be the KEY and the rest of the strucure is going to be de VALUE

其中编号将是该键和strucure的其余部分将是DE值

For example in a structure like this:

例如在这样的结构中:

[
      1: {
        name : "Peter",
        lastname : "Smith"
        age : 36
      },
    2: {
        name : "John",
        lastname : "Carlos"
        age : 40
      },
    ]

回答by Suneet Bansal

I written the below code as per your need, hope it will help you:

我根据您的需要编写了以下代码,希望对您有所帮助:

var data = [
                  {
                    id: 1,
                    name : "Peter",
                    lastname : "Smith",
                    age : 36
                  }, {
                    id: 2,
                    name : "Peter",
                    lastname : "Smith",
                    age : 36
                  }
                ];

                $scope.itemList = [];
                angular.forEach(data, function(item){
                    var obj = {};
                    var valObj = {};

                    valObj.name = item.name;
                    valObj.lastname = item.lastname;
                    valObj.age = item.age;

                    obj[item.id] = valObj;
                    $scope.itemList.push(obj);
                });

回答by tuananh

Hope this function will help you

希望这个功能能帮到你

$scope.transform = function(exportData){ var _value = {}; _value.name = exportData.name; _value.lastname = exportData.lastname; _value.age = exportData.age; var item = [exportData.id, _value]; $scope.list.push(item); }

$scope.transform = function(exportData){ var _value = {}; _value.name = exportData.name; _value.lastname = exportData.lastname; _value.age = exportData.age; var item = [exportData.id, _value]; $scope.list.push(item); }