Reputation: 598
[
{ "text": "demo1" },
{ "text": "demo2" }
]
to
["demo1", "demo2"]
I have tried using reduce()
Upvotes: 3
Views: 16449
Reputation: 116
If you are using underscore js it will be more easy to convert an array using pluck and more efficient then reduce .
var arr = [ {"text":"demo1"}, {"text":"demo2"}];
_.pluck(arr , 'text');
output:-
=> ["demo1", "demo2"]
Upvotes: 1
Reputation: 44959
You can use Array.prototype.map
for that:
var arr = [
{"text":"demo1"},
{"text":"demo2"}
];
var texts = arr.map(function(el) {
return el.text;
});
console.log(texts);
And with ES6, you can use arrow functions:
var texts = arr.map((el) => el.text);
Upvotes: 13
Reputation: 554
Try this:
var values = [
{"text":"demo1"},
{"text":"demo2"}
];
var log = [];
angular.forEach(values, function(value, key) {
this.push(value.text);
}, log);
alert(log);
Upvotes: 1
Reputation:
You can use map()
for this:
var myArray = [ {"text": "demo1"}, {"text": "demo2"} ];
var newArray = myArray.map( el => el.text); // [ "demo1", "demo2"]
Basically map()
performs an operation on every element of an array returning a new array.
It's hard to do this with reduce()
when you have such a small array, but still possible:
var myArray = [ {"text": "demo1"}, {"text": "demo2"} ];
var newArray = myArray.reduce( (a,b) => [a.text, b.text]) // [ "demo1", "demo2" ]
In this example a
is the first item and b
is the second item.
Upvotes: 3
Reputation: 50291
You can use forEach
to get text
from the array , Then use join to get the string
var a =[
{"text":"demo1"},
{"text":"demo2"}
]
var sArray = [];
a.forEach(function(item){
sArray.push(item.text)
})
var myString = sArray.join(',');
console.log(myString)
Alternatively you can also create a variable & concat
each item.text
Upvotes: 0