The Ninja
The Ninja

Reputation: 55

Javascript filter data based on the ID

I have an object that contains these data.

 {id: 1864,
 courseContentId: 481,
 fileName: GymMembership.jpg
 }
 {id: 1865,
 courseContentId: 481,
 fileName: Field.jpg
 }
 {id: 1866,
 courseContentId: 482,
 fileName: Track.jpg
 }

And i wanted to show them seperately on the view based on the courseContentId by creating a new object and this is my desired output.

 {id: 1864,
 courseContentId: 481,
 fileName: GymMembership.jpg
 }
 {id: 1865,
 courseContentId: 481,
 fileName: Field.jpg
 }

 {id: 1866,
 courseContentId: 482,
 fileName: Track.jpg
 }

What kind of javascript function is suitable for this?

Upvotes: 0

Views: 5069

Answers (3)

Arjun Kava
Arjun Kava

Reputation: 6081

Just use _.GroupBy, rather than applying multiple filters.

courses = [{id: 1864,
 courseContentId: 481,
 fileName: 'GymMembership.jpg'
 },
 {id: 1865,
 courseContentId: 481,
 fileName: 'Field.jpg'
 },
 {id: 1866,
 courseContentId: 482,
 fileName: 'Track.jpg'
 }]
 
var grouped = _.groupBy(courses, function(course) {
  return course.courseContentId;
});
console.log("Grouped")
console.log(grouped);
console.log("Filter by 481")
console.log(grouped["481"]);
console.log("Filter by 482")
console.log(grouped["482"]);
<script src="https://cdn.jsdelivr.net/lodash/4.17.2/lodash.min.js"></script>

Upvotes: 1

Stephen.W
Stephen.W

Reputation: 2127

let yourDesiredContentId = 481;
let result = array.filter(el => el.courseContentId === yourDesiredContentId);

Upvotes: 1

ACD
ACD

Reputation: 1431

Not really sure if there's an easy way to do that. Anyway, try this:

var test = [{
    id: 1864,
    courseContentId: 481,
    fileName: 'GymMembership.jpg'
  },
  {
    id: 1865,
    courseContentId: 481,
    fileName: 'Field.jpg'
  },
  {
    id: 1866,
    courseContentId: 482,
    fileName: 'Track.jpg'
  }
];

console.log(filter(test, 'courseContentId', 481));

function filter(arr, key, value) {
  return arr.reduce((data, item) => {
    if (item[key] == value) data.push(item);
    return data;
  }, []);
}

Upvotes: 0

Related Questions