[英]when assigning JSON data, not an array error in angularjs
This is my JSON data format. 这是我的JSON数据格式。
{
"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. 现在您可以了解为什么您的JSON数据不包含任何数组。 Instead of just assigning JSON's data directly to
$scope.Brands
, you can push the values like this: 不仅可以直接将JSON的数据分配给
$scope.Brands
,还可以像这样推送值:
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. 鉴于您使用的是angular,@ SSH已经给出了最佳答案。 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]);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.