[英]Simple method to return comma-separated values of object array
I have an object that looks like this: 我有一个看起来像这样的对象:
{
"id": "123",
"members": [
{ "id": 1, "name": "Andrew" },
{ "id": 2, "name": "Jim" }
]
}
I'd like a method to return a string of member names: "Andrew, Jim"
. 我想要一个返回一串成员名字的方法:
"Andrew, Jim"
。
As opposed to iterating through the member list and adding them to an array, is there a way to accomplish this cleanly in a single line (maybe underscore.js)? 与迭代成员列表并将它们添加到数组相反,有没有办法在一行中干净地完成这个(可能是underscore.js)?
members
is Array
of Objects
, first you need to create Array
with names - for this case you can use .map
and then convert this Array
to String
- to do that you can use .join
members
是Objects
Array
,首先需要创建带有名称的Array
- 在这种情况下,您可以使用.map
然后将此Array
转换为String
- 为此可以使用.join
var data = { "id": "123", "members": [ { "id": 1, "name": "Andrew" }, { "id": 2, "name": "Jim" } ] }; var result = data.members.map(function (e) { return e.name; }).join(', '); console.log(result);
something like 就像是
var arr = {
"id": "123",
"members": [
{ "id": 1, "name": "Andrew" },
{ "id": 2, "name": "Jim" }
]
};
console.log( arr.members.reduce( function(x,y){ return "\"" + x.name + "\", \"" + y.name + "\"" } ) );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.