wesley
wesley

Reputation: 137

Extract values from json string javascript

I am using a multiselect element from select2 to enter multiple "tags". When I want to get the value from the element I get something like this (for tag1 en tag2 which I entered in the box):

[{"id":"tag1","text":"tag1"},{"id":"tag2","text":"tag2"}] 

How do I get the result from text in an array something like this:

[0] = "tag1"
[1] = "tag2"

And how do I reverse this process?

Upvotes: 6

Views: 27302

Answers (3)

var data = JSON.parse('[{"id":"tag1","text":"tag1"},{"id":"tag2","text":"tag2"}] ');
data[0].id
data[1].id

Try this will help you

Upvotes: 1

nullpotent
nullpotent

Reputation: 9260

Here's another approach

[{"id":"tag1","text":"tag1"},{"id":"tag2","text":"tag2"}].map(function(el) {
 return el.id;
});

Upvotes: 9

Praveen
Praveen

Reputation: 56501

Try this simple iteration.

var obj = [{"id":"tag1","text":"tag1"},{"id":"tag2","text":"tag2"}] ;

for (var i =0; i< obj.length ;i++) {
   console.log(obj[i].id);
}

Upvotes: 6

Related Questions