[
{ "text": "demo1" },
{ "text": "demo2" }
]
to
["demo1", "demo2"]
I have tried using reduce()
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);
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.
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
underscore.js's pluck function. it's as easy as_.pluck(demoArray, 'text');