I have an array of nested objects, I want to filter this to return only the object tjat contains an author who's age === 21.
I've attempted to implement this SO answer, but I keep having 'x is not a function' returned.
let arrayOfElements =
[
{
author: { name: 'Kim', age: 21 },
employment: { employer: 'Logiothech', role: 'Human Resources' }
}
{
author: { name: 'John', age: 62 },
employment: { employer: 'Logiothech', role: 'Human Resources' }
}
{
author: { name: 'Mary', age: 31 },
employment: { employer: 'Logiothech', role: 'Human Resources' }
}
];
What I have tried: (I believe I'm incorrectly using subElements, but unsure what to correctly sub in it's place)
let filteredMap = array_of_elements.map((element) => {
return {...element, subElements: element.subElements.filter((subElement) => subElement.author.age === 21)}
})
You just need the .filter array method. the .map method is when you want to make a change to each element in the array. Here is what I came up with:
let filteredArray = arrayOfElements.filter((element) => element.author.age == 21)
Full code:
let arrayOfElements =
[
{
author: { name: 'Kim', age: 21 },
employment: { employer: 'Logiothech', role: 'Human Resources' }
},
{
author: { name: 'John', age: 62 },
employment: { employer: 'Logiothech', role: 'Human Resources' }
},
{
author: { name: 'Mary', age: 31 },
employment: { employer: 'Logiothech', role: 'Human Resources' }
}
];
let filteredArray = arrayOfElements.filter((element) => element.author.age == 21)
console.log(filteredArray)
I could be wrong, but it looks like you're overthinking it a bit. Try this:
arrayOfElements.filter(element => element.author.age === 21);
This will return an array of objects (in this case one) that have an author whose age is 21.