Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

139
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!