Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

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

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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

about 4 years ago · Juan Pablo Isaza Denunciar

0

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}']
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda