Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.

Let's say I have this Json ..

{
    "name": "Mark",
    "gender": "male",
    "account1": {
        "accountNo": 1201,
        "balance": 300
    },
    "account2": {
        "accountNo": 1354,
        "balance": 5000
    }
}    

What I expect is like ..

$scope.myArray = [
    {
        "accountNo": 1201,
        "balance": 300
    },
    {
        "accountNo": 1354,
        "balance": 5000
    }
];

In AngularJS, how can I pick some part of Json data and push it into an array iteratively( I mean, when I have account1, account2 account3 or more, it can still add them into the array).

share|improve this question

3 Answers 3

up vote 0 down vote accepted

You could normally just assign the array over, but in this scenario that is not an option because your array is psuedo.

Ideally you would like to be able to do what this answer (related question) does: How to return and array inside a JSON object in Angular.js which is simply

$scope.myArray = json.accounts;

However, as noted, you do not have an accounts array so you need to make one.

var accounts = [];
for(var key in json){
 if( !json.hasOwnProperty(key) // skip prototype extensions
  || !json[key].hasOwnProperty("accountNo") //skip non account objects
 ) continue; 
 accounts.push(json[key]);
}

And now you may use this array

$scope.myArray = accounts;
share|improve this answer

You can access Json data like an array. Like var foo = { ... , 'bar' = 'value', ... } you could get foo value by doing this for['bar']. So, by knowing this, you simply do something like

var arr = [];
for (var i = 0; i < 10; i++) {
    arr.push(foo['account'+i]);
}

Although, this has nothing to do with angularjs.

share|improve this answer
    
"Although, this has nothing to do with angularjs" is true, but all you need to do to make this answer complete from an angular perspective is to add $scope.myArray = arr; . Recognizing the key numbers in the object was smart, but also do note they start at 1 and not 0. And also, you would push a lot of undefined values into the array since the total number is unknown. –  Travis J Mar 28 at 22:40
    
About the numbers and undefined, I just wrote this as an abstract example, since, as I suppose, problem described abstract itself. –  Tomas Smagurauskas Mar 28 at 22:55

You can use JSON.parse() this will turn the JSON into a javascript object and then you can pull any data you want out of the object and push it into your own object. Read more at: http://www.w3schools.com/json/json_eval.asp

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.