简体   繁体   English

将对象数组转换为字符串数组

[英]Convert array of objects to array of strings

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

to

["demo1", "demo2"]

I have tried using reduce()我试过使用 reduce()

You can use Array.prototype.map for that:您可以使用Array.prototype.map

 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 :在 ES6 中,你可以使用箭头函数

var texts = arr.map((el) => el.text);

You can use map() for this:您可以为此使用map()

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.基本上map()对数组的每个元素执行操作,返回一个新数组。

It's hard to do this with reduce() when you have such a small array, but still possible:当你有这么小的数组时,用reduce()很难做到这一点,但仍然有可能:

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.在这个例子中, a是第一项, b是第二项。

Try this:试试这个:

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

If you are using underscore js it will be more easy to convert an array using pluck and more efficient then reduce .如果您使用下划线 js,那么使用 pluck 转换数组会更容易,并且效率更高,然后 reduce 。

var arr = [  {"text":"demo1"},  {"text":"demo2"}];    
_.pluck(arr , 'text');

output:-
=> ["demo1", "demo2"]

You can use forEach to get text from the array , Then use join to get the string您可以使用forEach从数组中获取text ,然后使用join获取字符串

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或者,您也可以创建一个变量并concat每个item.text

JSFIDDLE JSFIDDLE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM