javascript - 将对象数组转换为字符串 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);
解决方案
您可以首先使用或任何您喜欢的方式将数组转换为所需的对象.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'))
推荐阅读
- automation - 无法使用 Cypress 在 CK 编辑器中输入数据
- php - 限制已订阅的包裹购买
- javascript - react js中如何根据id依次显示一个api的数据?
- php - PHP POST 中的 413 请求实体太大错误
- python - Pytorch 中 NLLLoss 损失函数的 C 类是什么?
- unity3d - 用纹理填充贝塞尔曲线之间的区域
- java - 从 Flink 中的 ProcessWindowFunction 的上下文中获取 Collector 对象
- javascript - 案例功能不适用于不和谐机器人
- javascript - 不断更改图像 src / 内存使用情况(电子)
- python - 我如何在 mac os 上安装 quadprog