如何将一些数据从Json推送到AngularJS的新数组中? [英] How to push some data from Json into new array in AngularJS?

查看:95
本文介绍了如何将一些数据从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;

这篇关于如何将一些数据从Json推送到AngularJS的新数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆