3
[
  { "text": "demo1" },
  { "text": "demo2" }
]

to

["demo1", "demo2"]

I have tried using reduce()

1
  • you can also use underscore.js's pluck function. it's as easy as _.pluck(demoArray, 'text'); Commented Aug 12, 2016 at 9:07

5 Answers 5

13

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);
Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

1

Try this:

var values = [
{"text":"demo1"},
{"text":"demo2"}
];
var log = [];
angular.forEach(values, function(value, key) {
  this.push(value.text);
}, log);
alert(log);

Comments

1

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"]

Comments

0

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

JSFIDDLE

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.