简体   繁体   English

任何将nodejs对象转换为字符串的聪明方法

[英]any smart way to convert nodejs object to a string

The problem is coming from this discussion https://github.com/hashicorp/terraform/issues/11036#issuecomment-357334325 问题来自此讨论https://github.com/hashicorp/terraform/issues/11036#issuecomment-357334325

Terraform doesn't really understand multiple list, so I have to convert it to below format Terraform并不真正了解多个列表,因此我必须将其转换为以下格式

locals {
  test = [{
    a = "a1"
    b = "b1"
  },{
    a= "a2"
    b = "b2"
  }]
}

So suppose I have below object 所以假设我有下面的对象

[
  {
    "name": "a",
    "value": "foo"
  },
  {
    "name": "b",
    "value": "bar"
  },
  {
    "name": "c",
    "value": "boo"
  },
  {
    "name": "d",
    "value": "far"
  }
]

I'd like to convert to string as below: 我想转换为字符串 ,如下所示:

[ { name = "a", value = "foo" }, { name = "b", value = "bar" }, { name = "c", value = "boo" }, { name = "d", value = "far" } ]

The code I am currently working is to go through each key and export it with new format. 我当前正在工作的代码是遍历每个键并以新格式导出它。

$ cat a.js
var array1 = [{"name":"a","value":"foo"},{"name":"b","value":"bar"},{"name":"c","value":"boo"},{"name":"d","value":"far"}]

array1.forEach(function(element) {
  Object.keys(element).forEach(function(key) {
    console.log(key);
    console.log(element[key]);
  });
});

$ node a.js
name
a
value
foo
name
b
value
bar
name
c
value
boo
name
d
value
far

Any smart way to convert it, more than go through each key and export the key and value with nominated format? 除了转换每个键并以指定格式导出键和值之外,还有什么聪明的方法来转换它?

Regex replacing will do the job: 正则表达式替换将完成以下任务:

var array1 = [{"name":"a","value":"foo"},{"name":"b","value":"bar"},{"name":"c","value":"boo"},{"name":"d","value":"far"}]

a = JSON.stringify(array1);
a = a.replace(/\[|{|\]|}|"/g, "")
a = a.replace(/:|,/g, "\n");

console.log(a);

Updates 更新

Finally I go with @MrfksIV 's solution. 最后,我使用@MrfksIV的解决方案。

The limit is, there should be no space in any values. 限制是,任何值中都不能有空格。

var array1 = [{"name":"a","value":"foo"},{"name":"b","value":"bar"},{"name":"c","value":"boo"},{"name":"d","value":"far"}]

a = JSON.stringify(array1);
a = a.replace(/"/g, "")
a = a.replace(/:/g, "=")

console.log(a);

output is 输出是

 [{name=a,value=foo},{name=b,value=bar},{name=c,value=boo},{name=d,value=far}]

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

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