简体   繁体   中英

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

I have a list in 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:

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

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

For example in a structure like this:

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

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);
                });

希望此功能对您有帮助

$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); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM