Manoj Ghediya
Manoj Ghediya

Reputation: 17

Convert object to string while join array in javascript

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"}"

Upvotes: 0

Views: 106

Answers (2)

Shreekesh Murkar
Shreekesh Murkar

Reputation: 605

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}']

Upvotes: 0

brk
brk

Reputation: 50291

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)

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))

Upvotes: 2

Related Questions