首页 > 解决方案 > 将对象数组转换为字符串 es6

问题描述

我如何转换以下对象数组

let user =[
{key: "name", value: "xyz"},
{key: "friend", value: "abc"},
{key: "mobileno", value: "123"}];

成字符串输出,例如

"name:xyz
friend:abc
mobileno:123"

到目前为止,我已经做到了

let person = [
{key: "name ",value: "harsh" },
{key: "friend ",value: "dhruvil" }, 
{key: "mobileno ",value: "982559061" }];

var str = JSON.stringify(person); 
var newstr = str.replace(/[^a-xyz]/g, ''); 
console.log(newstr);

标签: javascriptecmascript-6

解决方案


您可以首先使用或任何您喜欢的方式将数组转换为所需的对象.reduce,例如

user.reduce((o, key) => Object.assign(o, {[key.key]: key.value}), {})

现在您可以将此对象转换为字符串,JSON.stringify然后使用.replace此字符串上的方法将大括号替换{

replace(/[\{\}]/g, "")

let user =[
{key: "name", value: "xyz", disabled: false},
{key: "friend", value: "abc ", disabled: true},
{key: "mobileno", value: "123", disabled: false}];

var x= user.reduce((o, key) => Object.assign(o, {[key.key]: key.value}), {});

console.log(JSON.stringify(x).replace(/[\{\}]/g, "").replace(/,/g, '\n'))


推荐阅读