If you ever tried to .join()
an array of objects, you might be surprised to get [object Object]
in the result.
let names = [
{
first: "Roger",
last: "McRogerson"
},
{
first: "Peter",
last: "Peterson"
},
{
first: "Jane",
last: "Janeson"
}
];
console.log(names.join());
// "[object Object],[object Object],[object Object]"
Annoying!
But that happens because the .join()
method turns any value into a string, and then joins the string together.
And if you turn an object into a string, you get the dreaded '[object Object]'
.
console.log(({ test: "test" }).toString());
// '[object Object]'
It happens with numbers also:
console.log([1, 2, 3, 4, 5].join(0));
// "102030405"
We've joined a bunch of numbers together with another number in between, but they have ended up as a string.
So we can't use Array.join()
on an array of objects - or can we?
Array.join()
for an object
I can't picture too many situations where you would want to join the whole array of objects into one long string*, but let's imagine for a moment that you do.
If you did want to join your array of objects, you can turn the objects into strings first using Array.map()
on the array, and JSON.stringify()
on the objects.
That will give you an array of strings that you can now use join()
on!
// map and join
console.log(names.map((name) => JSON.stringify(name)).join());
// '{"first":"Roger","last":"McRogerson"},{"first":"Peter","last":"Peterson"},{"first":"Jane","last":"Janeson"}'
*Unless you need it as a JSON string which comes up quite often, but you can use JSON.stringify(names)
if you want to turn your array into a JSON string.
Array.join()
for an object property
But what if you want a string of each person's first and last name, not as an object, but as an easy-to-read, regular sentence?
This is a much more realistic example of when you would want to use .join()
on an array of objects. And the principal will be similar. We need to create an array of strings (or numbers) before we use .join()
.
In this case, we want the first name and the last name. And we can use .map()
to get those object properties, before using .join()
.
let namesString = names.map((name) => `${name.first} ${name.last}`).join(", ");
console.log(namesString);
// "Roger McRogerson, Peter Peterson, Jane Janeson"
I've added a space after the comma by passing a string (", "
) to .join()
to use as the separator.
Let's break that down so it's really clear what is happening at each stage.
// the array of objects
let names = [
{
first: "Roger",
last: "McRogerson"
},
{
first: "Peter",
last: "Peterson"
},
{
first: "Jane",
last: "Janeson"
}
];
// create an array of the property values you need as strings
let namesValues = names.map((name) => `${name.first} ${name.last}`);
console.log(namesValues);
// ["Roger McRogerson", "Peter Peterson", "Jane Janeson"]
// join them to become a string with a comma separator
let joinedNames = namesValues.join(", ");
console.log(joinedNames);
// "Roger McRogerson, Peter Peterson, Jane Janeson"