[英]How to convert string to array in angularJS
Actually, I am receiving array in response with slashes so, I did this. 实际上,我收到数据以响应斜线所以,我这样做了。
what I receiving on the response 我收到的回复
[{\"name\":\"title\",\"value\":\"%post_title%\"},{\"name\":\"author\",\"value\":\"%author_name%\"}]
so I did this 所以我这样做了
var b=JSON.stringify(response.data);
var str = b.replace(/\\/g, '');
after this, I have a string like 在此之后,我有一个字符串
["{"name":"title","value":"%post_title%"}","{"name":"author","value":"%author_name%"}","{"name":"wordcount","value":"%wordcount%"}","{"name":"logged_in","value":"%logged_in%"}","{"name":"page_id","value":"%page_id%"}","{"name":"post_date","value":"%post_date%"}"]
now, how can I again covert this to the array so I use it in ng-repeat? 现在,我怎样才能再次将其转换为数组,以便在ng-repeat中使用它?
You should use JSON.parse()
to create an array: 您应该使用
JSON.parse()
来创建一个数组:
let str = '[{\\"name\\":\\"title\\",\\"value\\":\\"%post_title%\\"},{\\"name\\":\\"author\\",\\"value\\":\\"%author_name%\\"}]'; console.log(JSON.parse(str));
.as-console-wrapper { max-height: 100% !important; top: 0; }
你可以使用JSON.parse。
const myNewArray = JSON.parse(str);
use angular.fromJson()
使用
angular.fromJson()
$scope.x = '[{\"name\":\"title\",\"value\":\"%post_title%\"},{\"name\":\"author\",\"value\":\"%author_name%\"}]';
console.log(angular.fromJson($scope.x));
otherwise use JSON.parse()
否则使用
JSON.parse()
console.log(JSON.parse($scope.x));
You can use JSON.parse()
: 您可以使用
JSON.parse()
:
var array = JSON.parse(`[
{"name":"title", "value":"%post_title%"},
{"name":"author", "value":"%author_name%"}
]`);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.