2

I have a data structure like this:

[
   {firstName: "John",
    secondName: "Smith",
    children: ["Fred", "Hannah"]
   },
   {firstName: "Daniel",
    secondName: "Evans",
    children: ["Maggie", "Eddie", "Maria"]
   }
]

I want to use ng-repeat to return the CHILDREN of each person object, in a continuous list.

Like so:

<ul>    
    <li>Fred</li>
    <li>Hannah</li>
    <li>Maggie</li>
    <li>Eddie</li>
    <li>Maria</li>
</ul>

Can anyone help?

2
  • That is an array of objects, which has an array, try thinking of it like that and post some code on how you tried to access it. Commented Feb 25, 2016 at 21:07
  • Are you not outputting the parent? Also what have you tried? Commented Feb 25, 2016 at 21:14

1 Answer 1

2

You could reduce your data structure before presenting it to the ng-repeat.

var app = angular.module('myApp', [
  'my.controllers'
]);

var controllers = angular.module('my.controllers', []);

controllers.controller('MyController', function($scope) {
  var people = [{
    firstName: "John",
    secondName: "Smith",
    children: ["Fred", "Hannah"]
  }, {
    firstName: "Daniel",
    secondName: "Evans",
    children: ["Maggie", "Eddie", "Maria"]
  }, {
   firstName:"Childless",
   secondName: "Parent"
  },
  { 
   firstName:"Jeff",
   secondName: "Pasty",
   children: ["Mike"]
  }];

  $scope.allChildren = people.reduce(function(a, b) { return a.concat(b.children) },[]);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="MyController">
    <div ng-repeat='child in allChildren'>{{ child }}</div>
  </div>
</div>

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

4 Comments

small bug ... add another parent with children. reduce throws error since returning an array that doesn't have children property
could do people.reduce(function(a, b) { return a.concat(b.children) },[]);
@charlietfl Thankyou for pointing that out, very helpful, have edited to include your sugegstion
That's it! Can't believe it didn't occur to me to store it in a new variable. Great advice - thanks to both.

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.