如何将一些数据从Json推送到AngularJS的新数组中?

问题描述:

假设我有这个Json ..

Let's say I have this Json ..

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

我期望的是..

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

在AngularJS中,如何选择Json数据的一部分并将其迭代地推送到数组中(我的意思是,当我拥有account1,account2 account3或更多时,它仍然可以将它们添加到数组中).

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).

您通常可以将数组分配过来,但是在这种情况下,由于您的数组是psuedo,这是不可行的.

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

现在您可以使用此数组

$scope.myArray = accounts;