2017-04-11 129 views
1

我有以下代碼,我從JSON文件中獲取數據,我將數據存儲在$scope.users變量中,但我只想獲取用戶名值,我該如何做到這一點?JavaScript:如何從JSON數據獲取特定值

LoginCtrl.js

'use strict'; 
angular.module('User').controller('LoginCtrl', ['$scope','$state', "SettingService","UserService", function($scope,$state, SettingService,UserService) { 

$scope.users = []; 

    UserService.getLoginInfo().then(function(response){ 
    $scope.users = response.data.data["username"]; 
    }, function(error){ 

    }) 

    var vm = this; 

    vm.doLogin = function(){ 
     var username = document.forms["loginForm"]["email"].value; 
var password = document.forms["loginForm"]["password"].value; 
if(username == "[email protected]") 
{ 
    if(password == "admin") 
    { 
     $state.go('app.home'); 
    } 
} 
    }; 
}]); 

User.json

{ 
    "result": "success", 
    "data": [ 
     { "id": 1, "username":"[email protected]", "password":"admin"} 


    ] 
} 
+3

應該是'response.data.data [0] [ 「用戶名」]'的'內部數據'是一個數組 –

+0

'response.data.data [0] [「username」]' – Edison

+0

謝謝你這麼多@PankajParkar :) –

回答

2

您可以爲JSON值獲得價值

response.data.data[0]["username"] 

如果你想獲得的所有a中的用戶名rray,那麼你可以做這樣的事情:

var arr = response.data.map(function(a, b){ 
    return a.username; 
}); 

arr將包含所有的用戶名細節