简体   繁体   中英

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:

ab "{"name":"john", "age":22, "class":"mca"}"

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM