Home > Net >  How to use the method includes() or other methods so that i could filter the array to another that w
How to use the method includes() or other methods so that i could filter the array to another that w

Time:10-09

for example i have certain array which has the objects in it:

const people = [

{id: 1, name: 'Michael', age: 26},
{id: 2, name: 'Tom', age: 15},
{id: 3, name: 'Kevin', age: 56},
{id: 4, name: 'Christian', year: 1990},

]

now i need to filter it to the another array which will have the same properties excluding last as i said above, that is, i wanna have objects with property "age" in new array, here is my trying of realize it below:

const ages = array.filter((el, index, arr) => {
    if(arr.includes('age')){
        return true
    }
})
console.log(ages)

Javascript's interpreter returns undefined, what's wrong with my code? thanks to who will solve it

CodePudding user response:

You could run the filter method on the array and inside the filter condition, you could check the object's keys array for the 'age' attribute.

Here's the code for your response.

const ages = array.filter(person => Object.keys(person).includes('age'));
console.log(ages);
  • Related