[英]Taking key data from objects in Array and turning them into a , separated string
What method, or lodash function would you use to pull out the ids below and generate a comma separated string out of them? 您将使用哪种方法或lodash函数提取下面的ID,并从中生成逗号分隔的字符串?
var myArray = [
{
tag: 'wunwun',
id: 132
},
{
tag: 'davos',
id: 452
},
{
tag: 'jon snow',
id: 678
}
]
Like this: '132, '452', '678'
像这样:
'132, '452', '678'
No need to use a third-party library for that: 无需为此使用第三方库 :
var commaSeparatedIds = myArray.map(function(item) {
return item.id;
}).join(','); // result: '132,452,678'
Or if you just want them as an array, skip the join
: 或者,如果只希望将它们作为数组,则跳过
join
:
var commaSeparatedIds = myArray.map(function(item) {
return item.id;
}); // result: ['132', '452', '678']
References: 参考文献:
Use
Array#map
to get array ofid
and applyArray#join
over it.使用
Array#map
获取id
数组,并对其应用Array#join
。
var myArray = [{ tag: 'wunwun', id: 132 }, { tag: 'davos', id: 452 }, { tag: 'jon snow', id: 678 }]; var op = myArray.map(function(item) { return item.id; }); console.log(op.join(', '))
Well, this is easy: 好吧,这很容易:
_.pluck(myArray, 'id').join(', ')
_.map
works the same way, but you can also pass in a function instead of an array _.map
工作方式相同,但您也可以传入函数而不是数组
myArray.map(function(element){return element.id;}).join(',');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.