0

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?

1
  • 1
    your data is NOT an array, hence the error Commented Aug 14, 2016 at 4:40

3 Answers 3

2

You can use loop for this

  angular.forEach(data,function(value,key){
   $scope.Brands.push(value);
  })
Sign up to request clarification or add additional context in comments.

Comments

1

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="[email protected]" 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.

Comments

0

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]);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.