6

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?

1

3 Answers 3

9

Here's another approach

[{"id":"tag1","text":"tag1"},{"id":"tag2","text":"tag2"}].map(function(el) {
 return el.id;
});
Sign up to request clarification or add additional context in comments.

2 Comments

+1 Using map(), nice approach which returns those id to an array.
Sure is, if it's supported ;)
6

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

Comments

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

Try this will help you

1 Comment

This doesn't accomplish what OP is asking for. OP needed a programmatic solution, not a direct query. This wouldn't work in 1000 objects array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.