Reputation: 1655
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
Upvotes: 0
Views: 63
Reputation: 141829
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; } );
Upvotes: 3
Reputation: 150030
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:
.map()
method.join()
methodUpvotes: 1
Reputation: 1420
Iterate through autosuggest:
autosuggest.forEach(function(tag){ console.log(tag.text); }
Upvotes: 0