0

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)}
})
seanberlin
  • 161
  • 1
  • 8
  • 1
    You want to filter at the top level, not map. `let filteredMap = array_of_elements.filter(element => element.author.age === 21);` – pilchard Apr 01 '22 at 10:58
  • In your case, there is no prop named `subElements`. You may use a simple `.find` (or `.filter`, if you expect to have more than one matched results) to achieve your objective. Something like so: `arrayOfElements.find(x => x?.author?.age === 21);`. Here, `x` is just a placeholder - it symbolizes the current element being iterated from within the array. So, `x` has props same as the elements of the array. – jsN00b Apr 01 '22 at 10:58
  • 1
    also see: [Find object by id in an array of JavaScript objects](https://stackoverflow.com/questions/7364150/find-object-by-id-in-an-array-of-javascript-objects) – pilchard Apr 01 '22 at 11:00

2 Answers2

1

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)
EzioMercer
  • 1,502
  • 2
  • 7
  • 23
  • This is a duplicate and should be flagged for closure instead of answering. (also your answer is covered in my comment above ;) ) – pilchard Apr 01 '22 at 11:00
0

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.

edlinkiii
  • 19
  • 5