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?

wesley
  • 137
  • 1
  • 2
  • 6
  • 1
    possible duplicate of [Access / process (nested) objects, arrays or JSON](http://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) – Felix Kling Nov 22 '13 at 10:22

3 Answers3

9

Here's another approach

[{"id":"tag1","text":"tag1"},{"id":"tag2","text":"tag2"}].map(function(el) {
 return el.id;
});
nullpotent
  • 9,162
  • 1
  • 31
  • 42
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);
}
Praveen
  • 55,303
  • 33
  • 133
  • 164
1
var data = JSON.parse('[{"id":"tag1","text":"tag1"},{"id":"tag2","text":"tag2"}] ');
data[0].id
data[1].id

Try this will help you

  • 2
    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. – whoisjuan May 23 '18 at 06:56