Deekshith S
Deekshith S

Reputation: 281

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?

Upvotes: 3

Views: 2318

Answers (4)

Anshul Jindal
Anshul Jindal

Reputation: 1

You can use JSON.parse():

var array = JSON.parse(`[
    {"name":"title",  "value":"%post_title%"}, 
    {"name":"author", "value":"%author_name%"}
]`);

Upvotes: -1

Jignesh Joisar
Jignesh Joisar

Reputation: 15105

use angular.fromJson()

$scope.x = '[{\"name\":\"title\",\"value\":\"%post_title%\"},{\"name\":\"author\",\"value\":\"%author_name%\"}]';

 console.log(angular.fromJson($scope.x));

otherwise use JSON.parse()

console.log(JSON.parse($scope.x));

Upvotes: 0

Mohammad Usman
Mohammad Usman

Reputation: 39322

You should use JSON.parse() to create an array:

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; }

Upvotes: 2

Faheem
Faheem

Reputation: 1166

You can use JSON.parse for that.

const myNewArray = JSON.parse(str);

Upvotes: 1

Related Questions