0

I have an Object which contains values as follow

[{"text":"Tag1"},{"text":"Tag2"},{"text":"Tag3"}]

These are in the variable autosuggest. Now I want to get only the values

Tag1, Tag2, Tag3 

I´ve tried to do this

var textOnly = autosuggest.text 

But then, I get an "undefined" of

var textOnly = autosuggest[0]

Then I get only the first string, 'Tag1'

Thank you for your tips

mm1975
  • 1,583
  • 4
  • 30
  • 51

3 Answers3

3

You can use Array.prototype.map to iterate through the array and get each elements text property:

var result = autosuggest.map( function( tag ) { return tag.text; } );
Paul
  • 139,544
  • 27
  • 275
  • 264
1

If you're saying you want to get a string that is a comma-separated list of the values, then this will do it:

var textOnly = autosuggest.map(function(el){
                 return el.text;
               }).join(", ");
// "Tag1, Tag2, Tag3"

If you want to get an array that contains three elements, each of which being a string with one tag name in it, then leave off the .join() part:

var textOnlyArray = autosuggest.map(function(el){
                      return el.text;
                    });
// ["Tag1", "Tag2", "Tag3"]

More information at MDN:

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
0

Iterate through autosuggest:

autosuggest.forEach(function(tag){ console.log(tag.text); }
Phill Treddenick
  • 1,340
  • 13
  • 18