gpt4 book ai didi

javascript - 在JS中将字符串转换为数组

转载 作者:行者123 更新时间:2023-11-30 07:31:17 24 4
gpt4 key购买 nike

在我的项目中,我有一个如下的用例:

我有一个如下所示的响应数组,

(4) [{…}, {…}, {…}, {…}]
0:{header: 0, name: "Name", field: "Id"}
1:{header: 3, name: "LastName", field: "Agreement__c"}
2:{header: 3, name: "LastName", field: "Amount__c"}
3:{header: 3, name: "LastName", field: "BIC__c"}
length:4

从上面我通过使用将上面的数组转换为字符串,

JSON.stringify(responseArray) 并将其存储在字符串字段中。

之后,我想对该字段的值进行一些动态操作。所以当我从字段中取回值时,它如下所示,

[{"header":0,"name":"Name","field":"Id"}, 
{"header":3,"name":"LastName","field":"Agreement__c"},
{"header":3,"name":"LastName","field":"Amount__c"},
{"header":3,"name":"LastName","field":"BIC__c"}]

任何人都请帮助我将上面的字符串响应转换为 Javascript 中的数组,如下所示,

index 0 -> {"header":0,"name":"Name","field":"Id"}
index 1 -> {"header":3,"name":"LastName","field":"Agreement"}

我已经尝试过拆分功能,但无法实现确切的需求。

最佳答案

将方括号放在字符串的开头和结尾并调用 JSON.parse:

 $ node

> const text = `{"header":0,"name":"Name","field":"Id"},
{"header":3,"name":"LastName","field":"Agreement"},
{"header":3,"name":"LastName","field":"Amount"},
{"header":3,"name":"LastName","field":"BIC"}`

> JSON.parse(`[${text}]`)
[ { header: 0, name: 'Name', field: 'Id' },
{ header: 3, name: 'LastName', field: 'Agreement' },
{ header: 3, name: 'LastName', field: 'Amount' },
{ header: 3, name: 'LastName', field: 'BIC' } ]

关于javascript - 在JS中将字符串转换为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52070270/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com