简体   繁体   中英

when assigning JSON data, not an array error in angularjs

This is my JSON data format.

{
"0": {
    "id": "1",
    "image": "/images/brands/surf_excel.png",
    "name": "Surf Excel",
    "productCount": "6"
},
"1": {
    "id": "2",
    "image": "/images/brands/rin.png",
    "name": "Rin",
    "productCount": "5"
},
"2": {
    "id": "3",
    "image": "/images/brands/ariel.png",
    "name": "Ariel",
    "productCount": "4"
}
}

When i am trying to assign this data like this..

$scope.Brands = [];
$scope.Brands = data; // Not an array error

Basically i want to assign data and access one by one.

How to fix this error?

You can use loop for this

  angular.forEach(data,function(value,key){
   $scope.Brands.push(value);
  })

Always remember, Whenever there's an array, it would be surrounded by square brackets [ ] .

Now you can see why your JSON data doesn't contain any array. Instead of just assigning JSON's data directly to $scope.Brands , you can push the values like this:

 var app = angular.module('plunker', []); app.controller('MainCtrl', function($scope) { var data = JSON.parse('{"0":{"id":"1","image":"/images/brands/surf_excel.png","name":"Surf Excel","productCount":"6"},"1":{"id":"2","image":"/images/brands/rin.png","name":"Rin","productCount":"5"},"2":{"id":"3","image":"/images/brands/ariel.png","name":"Ariel","productCount":"4"}}'); $scope.name = 'World'; $scope.Brands = []; angular.forEach(data,function(value,key){ $scope.Brands.push(value); }) document.write("<pre>" + JSON.stringify($scope.Brands, 0, 8) + "</pre>"); }); 
 <!DOCTYPE html> <html ng-app="plunker"> <head> <meta charset="utf-8" /> <title>AngularJS Plunker</title> <script>document.write('<base href="' + document.location + '" />');</script> <link rel="stylesheet" href="style.css" /> <script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script> <script src="app.js"></script> </head> <body ng-controller="MainCtrl"></body> </html> 

Now when you run this snippet, you'll see the data surrounded by [ and ] . This indicates that it's an array.

Given you are using angular, @SSH has already given the best answer. Another way to solve this is (non angular):

var brands = new Array();

//Get the keys and iterate through them and add each entry
Object.keys(data).forEach(function(key){
    brands.push(data[key]);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM