最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

angularjs - JavaScript: How to get specific value from JSON data - Stack Overflow

programmeradmin1浏览0评论

I have the following code in which I fetch data from the JSON file , I Store data in $scope.users variable, But I want to fetch only username value how can I do this?

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"}


    ]
}

I have the following code in which I fetch data from the JSON file , I Store data in $scope.users variable, But I want to fetch only username value how can I do this?

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"}


    ]
}
Share Improve this question asked Apr 11, 2017 at 12:18 maria salahuddinmaria salahuddin 1252 gold badges4 silver badges16 bronze badges 4
  • 3 It should be response.data.data[0]["username"] as the inner data is an array – Pankaj Parkar Commented Apr 11, 2017 at 12:21
  • response.data.data[0]["username"] – Edison Augusthy Commented Apr 11, 2017 at 12:22
  • thankyou so much @PankajParkar :) – maria salahuddin Commented Apr 11, 2017 at 12:29
  • thanks @Edison :') – maria salahuddin Commented Apr 11, 2017 at 12:29
Add a ment  | 

1 Answer 1

Reset to default 2

you can get value for that JSON value as

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

If you want to get all the usernames from the array, then you can do something like this:

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

arr will contain all the username details

发布评论

评论列表(0)

  1. 暂无评论