1

So for example I have a MAIN array with all the information I need:

  $scope.songs = [
    { title: 'Reggae',  url:"#/app/mworkouts", id: 1 },
    { title: 'Chill',   url:"#/app/browse",    id: 2 },
    { title: 'Dubstep', url:"#/app/search",    id: 3 },
    { title: 'Indie',   url:"#/app/search",    id: 4 },
    { title: 'Rap',     url:"#/app/mworkouts", id: 5 },
    { title: 'Cowbell', url:"#/app/mworkouts", id: 6 }
  ];

I want to put only certain objects into another array without typing in each of the objects so the end result will look like

  $scope.array1 = [
    { title: 'Reggae', url:"#/app/mworkouts",id: 1 },
    { title: 'Cowbell', url:"#/app/mworkouts",id: 6 }
  ];

I have tried this with no luck:

  $scope.array1 = [
    { $scope.songs[1] },
    { $scope.songs[6] }
  ];

I will have to do a bunch of these so typing in each object would take forever, is there any faster way to do this? Thanks in advance :)

2
  • 2
    $scope.array1 = [ $scope.songs[1] , $scope.songs[6] ]; Commented Oct 19, 2016 at 18:48
  • 1
    Awesome! It's hard not knowing the correct syntax...thanks again! Commented Oct 19, 2016 at 18:59

2 Answers 2

2

You need to do something like this:

$scope.array1 = $scope.songs.filter(function (song) {
  return (song.title == "Reggae" || song.title == "Cowbell");
});

Here, the filter function will give you a filtered new array to be replaced for the original scope value.

console

Or in simple way, using the array indices, you can use:

$scope.array1 = [ $scope.songs[0] , $scope.songs[5] ];
Sign up to request clarification or add additional context in comments.

2 Comments

Keeping things simple and sexy, is there a way I could change some information in the object but keep all the other information the same? For Example, change just the id:1 to id:45 while still keeping title and url the same.
@MehdiN Yes, you can do it.. Just add song.id += 44; before the return statement. LoL. Might have undesirable effects.
1

You need to remove the braces since it's already an object. Although the array index starts from 0 so change index value based on 0.

$scope.array1 = [ 
   $scope.songs[0] ,
   $scope.songs[5] 
];

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.