1

I have a List of cars assigned to a person for a particular month. If you search April you will get April data. How do I access Nested JSON data via Index?

Here's plunker

   $scope.cars = $scope.results[resultIndex].cars.map(function(car) {
          return {
        make: car.Make,
            year: car.Year
          };
        });

   $scope.showCars = function(resultIndex) {
      $scope.cars = $scope.results[resultIndex].cars;
    };

      "April": [{
            "Name": "Tim",
                "Address": "Street",
                "Phone": "111",
                "Status": "Speeding",
                "cars": [
                  {
                    "Make": "Honda",
                    "Year": "2000"
                   }, 
                  {
                    "Make": "Ford",
                    "Year": "2010"
                  },
                  {
                    "Make": "Toyota",
                    "Year": "2004"
                  }

            ]},
2
  • Hi, what do you mean nested JSON by index, you mean an array inside an object? Like obj = {array: [1,2,3,4]} ? Commented May 5, 2015 at 22:35
  • I would like to pull the car make and year out... Commented May 5, 2015 at 22:56

1 Answer 1

4

Theres a few things you should first

Now to the code, you should really simplify your logic. Your data structure is all there and you haven't changed it much every time you search for something, so theres no need to map or loop the data - you should only need that if you need to do something with the data.

Your click button function can be as simple as

$scope.clickButton = function(enteredValue) {
    $scope.reset();
    $scope.results = data[enteredValue];
}

Change ur showCars function to

$scope.showCars = function(car) {
    $scope.cars = car;
};

in your html simply change the showCars function call to

<td ng-click='showCars($index)'>{{result.name}}</td>

Remove this, you wont need it

$scope.cars = $scope.results[resultIndex].cars.map(function(car) {
      return {
    make: car.Make,
        year: car.Year
      };
    });

EDIT

Heres the result http://plnkr.co/edit/LGytByq0d3a7AORxXsHa?p=preview

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Yang. I tried that but it didn't work. I'll keep at it.
Opps, I've given you the wrong plunk, check the updated answer @Angular_Newbie

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.