I have array of object and I want to convert this to comma separated object.
let arr = [{name:"k"},{name:"p"}];
console.log(...arr.join(','));
I'm getting this [ o b j e c t O b j e c t ] , [ o b j e c t O b j e c t ] I want to in this format {name:"k"},{name:"p"}. please help. thanks in advance.
CodePudding user response:
The default conversion of plain objects to strings results in "[object Object]"
. (More about why you got the specific output you got below.) If you want something different, you have to do that with your own code.
For instance, you could use map
to convert the objects to strings, then use join
on the result:
const result = arr.map(({name}) => `{name: ${JSON.stringify(name)}`).join(",");
Live Example:
let arr = [{name:"k"},{name:"p"}];
const result = arr.map(({name}) => `{name: ${JSON.stringify(name)}}`).join(",");
console.log(result);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
That just does the one specific property of course. If you want to include others, you'll need a loop/mapping operation in the map
callback (perhaps starting with Object.entries
on the object).
const result = arr.map(obj => {
const props = Object.entries(obj).map(([name, value]) => `${name}: ${JSON.stringify(value)}`);
return `{${props}}`;
}).join(",");
Live Example:
let arr = [{name:"k"},{name:"p"}];
const result = arr.map(obj => {
const props = Object.entries(obj).map(([name, value]) => `${name}: ${JSON.stringify(value)}`);
return `{${props}}`;
}).join(",");
console.log(result);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
If you don't mind quotes around the property names, then as shobe said you can do that by applying JSON.stringify
to the entire object.
const result = arr.map(obj => JSON.stringify(obj)).join(",");
But your question didn't show quotes around property names.
Live Example:
let arr = [{name:"k"},{name:"p"}];
const result = arr.map(obj => JSON.stringify(obj)).join(",");
console.log(result);
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Why you got the specific result you got:
I was initially surprised by the output you got, but it does make sense after a moment's thought: Your code does console.log(...arr.join(","))
, which does this:
- Calls
join
onarr
, which combines its entries together into a string using their default convert-to-string behavior, with a single comma in-between. - Spreads out that string into discrete arguments to
console.log
as though you'd writtenconsole.log("[", "o", "j"
etc.
CodePudding user response:
In order to convert object to it's string representation, you need to use JSON.stringify function. So it would look like this:
let arr = [{name:"k"},{name:"p"}];
console.log(arr.map(el => JSON.stringify(el)).join(','));