user image

Gulafsan Shaheen
Published in : 2022-03-05

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 Date : 2022-03-05

Best answers

10

Best answers

10

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!

Leave a comment

Join us

Join our community and get the chance to solve your code issues & share your opinion with us

Sign up Now

Related posts

javascript: Uncaught TypeError: undefined is not a function
Publish date: 2022-03-02 | Comments: 2

Tag: Javascript

jquery undefined function
Publish date: 2022-02-28 | Comments: 1

Tag: Javascript

What is the use of package-lock JSON file?
Publish date: 2022-02-11 | Comments: 3

Tag: Javascript

Coping plain text into form bug.
Publish date: 2022-02-11 | Comments: 1

Tag: Javascript

How can I switch between two background-colors using js setinterval( )
Publish date: 2022-02-22 | Comments: 1

Tag: Javascript

How select specific tag in jQuery using if else statement?
Publish date: 2022-02-27 | Comments: 1

Tag: Javascript