I want to convert array to string & if array contain object then need to convert in string.
array = [
'a',
'b',
{ name: 'John doe', age: 25 }
]
My code:
const convertedArray = array.join(' ');
Output like below:
a b "{"name":"john", "age":22, "class":"mca"}"
CodePudding user response:
You can use array reduce function. Inside the reduce callback check if the current object which is under iteration is an object or not. If it is an object then use JSON.stringify
and concat with the accumulator.
const array = [
'a',
'b',
{
name: 'John doe',
age: 25
}
];
const val = array.reduce((acc, curr) => {
if (typeof curr === 'object') {
acc = JSON.stringify(curr);
} else {
acc = `${curr} `
}
return acc;
}, '');
console.log(val)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Using JSON.stringify on the entire array
will have starting and ending [
and ]
respectively, which is not what you are looking
const array = [
'a',
'b',
{
name: 'John doe',
age: 25
}
];
console.log(JSON.stringify(array))
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
Simple ! Try following :
var arr = [
'a',
'b',
{ name: 'John doe', age: 25 }
]
var newArr = arr.map(i => typeof i === "object" ? JSON.stringify(i) : i)
console.log(newArr)
output :
['a', 'b', '{"name":"John doe","age":25}']