简体   繁体   English

在javascript中加入数组时将对象转换为字符串

[英]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"}" 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.在reduce 回调中检查当前正在迭代的对象是否是一个对象。 If it is an object then use JSON.stringify and concat with the accumulator.如果它是一个对象,则使用JSON.stringify并与累加器连接。

 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在整个array上使用 JSON.stringify 将分别有开始和结束[] ,这不是你想要的

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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