1

I have a dataset that looks like this:

[
  {
    'title' : 'cats',
    'names' : [
      'felix',
      'tom',
      ... more names
    ]
  },
  {
    'title' : 'dogs',
    'names' : [
      'fido',
      'rover',
      ... more names
    ]
  },
  {
    ... More animal types
]

And I would like to have the following:

<p ng-repeat='name in names'>{{ name }}</p>

But, to do that I really need to at some stage set

$scope.names = ['felix', 'tom', 'fido', rover'];

My question is: is there an 'Angular' way to merge arrays or take content from multiple places from one object? Or do I need to use a for loop with a concat function to create the array I use?

2
  • you would need to do your data mapping Commented May 15, 2015 at 14:41
  • Could you try an outer 'loop' of animal in animals and an inner one of name in animal.names? I'm not sure if that would work, or is idiomatic, so I'm not posting it as an answer. Commented May 15, 2015 at 14:42

2 Answers 2

2

Sure, just defined names based on your data, demo.

$scope.names = function() {
  return Array.prototype.concat.apply([], animals.map(function(animal) {
    return animal.names;
  }));
};

Then use that method in your view

<p ng-repeat='name in names()'>{{ name }}</p>

Or we could assume the list of animals won't change, and use a library like lodash for readability, demo.

$scope.names = _.chain(animals)
  .pluck('names')
  .flatten()
  .value()
Sign up to request clarification or add additional context in comments.

Comments

0

It is not likely to be a core functions for such feature in javascript nor in angular as angular is just mvc framework on javascript. function you need is not common enough for javascript, or specific enough for mvc

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.