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

to

["demo1", "demo2"]

I have tried using reduce()

str
45.5k18 gold badges117 silver badges134 bronze badges
asked Aug 12, 2016 at 8:27
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);
answered Aug 12, 2016 at 8:30
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.

answered Aug 12, 2016 at 8:32

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);
answered Aug 12, 2016 at 8:34

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"]
answered Aug 12, 2016 at 8:43

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

answered Aug 12, 2016 at 8:30

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.