0

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
      },
    ]
3
  • I still don't get what you currently have, what the problem is, and what's your expected result.. Commented May 23, 2016 at 4:30
  • but export data shouldn't be an array? Commented May 23, 2016 at 4:33
  • Hi @choz What I have is just the reponse in JSON, and I was looking for something similar to a "map" in JS and AngularJS, my problem is that I dont know if there's something similar to a map in JS like for example in Java where you can declare a map object and then how can I fill that map with the values coming in my reponse, in this case is json format. Commented May 23, 2016 at 4:51

2 Answers 2

4

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);
                });
Sign up to request clarification or add additional context in comments.

2 Comments

Thank's for your time!
Hi Sunnet, one more question, according to this script how can I avoid pushing the value if the id already exists?
1

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

1 Comment

Thanks for your time, I'll try this =)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.