如何在JavaScript中将数组中的对象转换为独立对象?
解决方法
首先得明确:在JavaScript语法里,直接写{...}, {...}, {...}这种用逗号分隔的多个独立对象是不合法的(除非是在对象属性、数组或者函数参数等特定场景里)。如果你是想生成这种格式的文本内容,可以用下面两种方式处理:
方法1:转JSON字符串后拼接
通过map把每个对象转成带缩进的JSON字符串,再用join添加逗号和换行,适合需要标准JSON格式的场景:
const arr = [ { public_id: 'apple', secure_url: 'one' }, { public_id: 'banana', secure_url: 'two' }, { public_id: 'orange', secure_url: 'three' } ]; // 转换为目标格式的字符串 const formattedStr = arr .map(obj => JSON.stringify(obj, null, 2)) // 每个对象转成带缩进的JSON字符串 .join(',\n'); console.log(formattedStr);
运行后输出:
{ "public_id": "apple", "secure_url": "one" }, { "public_id": "banana", "secure_url": "two" }, { "public_id": "orange", "secure_url": "three" }
方法2:手动拼接字符串
如果要完全匹配你给出的无引号属性名格式,可以直接拼接字符串(注意:仅适用于属性值为无特殊字符的字符串场景):
const arr = [ { public_id: 'apple', secure_url: 'one' }, { public_id: 'banana', secure_url: 'two' }, { public_id: 'orange', secure_url: 'three' } ]; const formattedStr = arr .map(obj => `{ public_id: '${obj.public_id}', secure_url: '${obj.secure_url}' }`) .join(',\n'); console.log(formattedStr);
运行后输出和你期望完全一致的内容:
{ public_id: 'apple', secure_url: 'one' }, { public_id: 'banana', secure_url: 'two' }, { public_id: 'orange', secure_url: 'three' }
内容的提问来源于stack exchange,提问作者Abu Sayem
相关产品推荐
相关产品推荐

