Gulafsan Shaheen

5 Mar 2022

Javascript: Filtering arrays by it properties?

Javascript

I have create a dataset which comprises of object, I want them to be filtered by their property values.

{id: 1, title: Anne, Finalist: true}, 
{id:2, title: Sam, Finalist: false},
{id:3, title: Lexi, Finalist: true}

I want to filter object which propety Finalist is true.

RESULT:

{id: 1, title: Tom, Finalist: true}, 
{id:3, title: Jake, Finalist: true}

Please help me!

Comments

Shilpa

5 Mar 2022

github

You can do with reduce API from Javascript.

Your objects input: 

var yourObj = {
 item1: {"id": 1, "title": "Anne", "Finalist": true}, 
 item2: {"id":2, "title": "Sam", "Finalist": false},
 item3: {"id":3, "title": "Lexi", "Finalist": true}
};

var allowed = ['item1', 'item3'];

var filteredObj = Object.keys(yourObj)
 .filter(key => allowed.includes(key))
 .reduce((obj, key) => {
 obj[key] = yourObj[key];
 return obj;
 }, {});

console.log(filteredObj ); // It will return participants where Finalist is true.

Hope it helps!

© 2024 Copyrights reserved for web-brackets.com