VIK6Galado
VIK6Galado

Reputation: 680

How to get values in an array of objects?

I want to collect all the movie id's where in rating is above 3 from the below array

let movies = [
  {'name': 'Actions', 'movies': [{'id': 1, 'rating': 2}, 
                                 {'id': 2, 'rating': 1}, 
                                 {'id': 3, 'rating': 4}]},
  {'name': 'Comedy', 'movies': [{'id': 4, 'rating': 3}, 
                                 {'id': 5, 'rating': 4}, 
                                 {'id': 6, 'rating': 5}]},
  {'name': 'Sci-fi', 'movies': [{'id': 7, 'rating': 1}, 
                                 {'id': 8, 'rating': 5}, 
                                 {'id': 9, 'rating': 2}]}
];

I'm getting the id's with rating above 3 from below code

let res = movies
          .map( m => m.movies
                    .filter( f => f.rating > 3 ) 
          )
          .flat();
console.log(res);

output

[[object Object] {
  id: 3,
  rating: 4
}, [object Object] {
  id: 5,
  rating: 4
}, [object Object] {
  id: 6,
  rating: 5
}, [object Object] {
  id: 8,
  rating: 5
}]

How can i get rid of [object Object] and rating from my output and get only flatted id's array?

Upvotes: 0

Views: 83

Answers (3)

Rahul Pandey
Rahul Pandey

Reputation: 73

You can get the desired output by adding map(rw => rw.id) after flat function.

let res = movies
          .map( m => m.movies
                    .filter( f => f.rating > 3 ) 
          )
          .flat().map(rw => rw.id);
console.log(res);

Upvotes: 1

Ankita Kuchhadiya
Ankita Kuchhadiya

Reputation: 1282

You can use a forEach() loop:

const movies = [{
  "name": "Actions",
  "movies": [{
    "id": 1,
    "rating": 2
  }, {
    "id": 2,
    "rating": 1
  }, {
    "id": 3,
    "rating": 4
  }]
}, {
  "name": "Comedy",
  "movies": [{
    "id": 4,
    "rating": 3
  }, {
    "id": 5,
    "rating": 4
  }, {
    "id": 6,
    "rating": 5
  }]
}, {
  "name": "Sci-fi",
  "movies": [{
    "id": 7,
    "rating": 1
  }, {
    "id": 8,
    "rating": 5
  }, {
    "id": 9,
    "rating": 2
  }]
}];

let result = [];

movies.forEach(({movies}) => {
  var movie3 = movies.filter(({rating}) => rating > 3).map(({id}) => id);
  result = [...result, ...movie3];
});
console.log(result);

Upvotes: 1

Ori Drori
Ori Drori

Reputation: 191976

Flatten the movies to an array using Array.flatMap(), filter by the rating, and then map to ids:

const movies = [{"name":"Actions","movies":[{"id":1,"rating":2},{"id":2,"rating":1},{"id":3,"rating":4}]},{"name":"Comedy","movies":[{"id":4,"rating":3},{"id":5,"rating":4},{"id":6,"rating":5}]},{"name":"Sci-fi","movies":[{"id":7,"rating":1},{"id":8,"rating":5},{"id":9,"rating":2}]}];

const result = movies
  .flatMap(m => m.movies)
  .filter(m => m.rating > 3)
  .map(m => m.id);

console.log(result);

Upvotes: 2

Related Questions