Let's assume that we are working with the following object:
javascriptlet people = { Andrea: {age: 27}, Erik: {age: 30}, Jaruwan: {age: 26}, Paula: {age: 15} }
We want to get an array with the people whose age is > 18:
javascriptlet adults = Object.values(people).map(name => name.age > 18 ? name.age : null); console.log(adults); // [27, 30, 26, null]
If the value is null, we don't want to insert it into the array:
javascriptlet adults = Object.values(people).map(name => name.age > 18 ? name.age : null); let filtered = adults.filter(age => age !== null); console.log(filtered); // [27, 30, 26]
In one line of code:
javascriptlet filtered = Object.values(people).map(name => name.age > 18 ? name.age : null).filter(age => age !== null); console.log(filtered); // [27, 30, 26]
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.