ketan pradhan
ketan pradhan

Reputation: 598

Convert array of objects to array of strings

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

to

["demo1", "demo2"]

I have tried using reduce()

Upvotes: 3

Views: 16449

Answers (5)

kuldeep kumar joshi
kuldeep kumar joshi

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

str
str

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

Dhananjay
Dhananjay

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

user5466293
user5466293

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

brk
brk

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

JSFIDDLE

Upvotes: 0

Related Questions