Explain Codes LogoExplain Codes Logo

Perform .join on value in array of objects

javascript
map-function
join-method
array-manipulation
Nikita BarsukovbyNikita Barsukov·Oct 20, 2024
TLDR

To obtain a string of concatenated property values from an array of objects, .map() and .join() come to your rescue. Here's the prime cut:

const arrayObj = [{ key: 'Red' }, { key: 'Green' }, { key: 'Blue' }]; const result = arrayObj.map(obj => obj.key).join(', '); // "Red, Green, Blue"

Map & join… Batman & Robin!

Much like Batman and Robin make a dynamic duo, the .map() and .join() functions combine to form a powerful team in JavaScript.

const superheroes = [{ name: 'Batman' }, { name: 'Robin' }, { name: 'Aquaman' }]; const heroNames = superheroes.map(hero => hero.name).join(', '); // "Batman, Robin, Aquaman"

Arrow functions, saving the day

Our superhero, the ECMAScript 6 arrow function, swoops in to inject readability and brevity into the array callbacks:

const animals = [{ name: 'Lion' }, { name: 'Tiger' }, { name: 'Bear' }]; const joinedAnimalNames = animals.map(({ name }) => name).join('; '); // Lions and Tigers and Bears; Oh my!

Nested properties, you’ve met your match

Handling nested properties? Fear not. Destructuring gives you access:

const users = [{ id: 1, profile: { name: 'Sam', city: 'New York' } }, ...]; const userNames = users.map(({ profile: { name, city } }) => `${name} from ${city}`).join(', ');

Old browsers, we’ve got you

For older browsers, utilize a polyfill for the .map() function. The MDN documentation provides solid options.

Reduce — an undercover alternative

.reduce()—a sneaky superhero in disguise, can operate alternatively to .map().join(), eliminating intermediate arrays:

const arrayObj = [{ key: 'foo' }, { key: 'bar' }, ...]; const result = arrayObj.reduce( (soFar, { key }, i) => `${soFar}${i ? ', ' : ''}${key}`, '' // We have a Hulk... a string Hulk! );

Custom join behavior — your secret weapon

Control the .join() behavior by declaring a custom toString within your array objects:

const arrayObj = [{ key: 'foo', toString() { return `Key: ${this.key}`; } }, ...]; const result = arrayObj.join(', '); // "Key: foo, Key: bar, ..."