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
您可以使用Array.prototype.map遍历数组并获取每个元素的text
属性:
var result = autosuggest.map( function( tag ) { return tag.text; } );
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()
method 通过自动建议进行迭代:
autosuggest.forEach(function(tag){ console.log(tag.text); }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.