我想基于键来连接数组中的项目。我通过lodash库试图_.join
,_.merge()
,_.groupBy()
,但似乎没有。你如何根据他们的密钥加入数组中的项目?
var myArray = [
{name: 'cheesesteak'},
{name: 'hamburger'},
{name: 'pork roll'}
];
var jawn = myArray.join();
console.log(jawn);
理想的输出是......
"chessesteak, hamburger, pork roll"
答案 0 :(得分:5)
使用 map()
和ES6 arrow function生成字符串数组,然后应用 join()
方法。
var myArray = [{
name: 'cheesesteak'
}, {
name: 'hamburger'
}, {
name: 'pork roll'
}];
var jawn = myArray.map(v => v.name).join();
console.log(jawn);

由于箭头功能仅支持在最新浏览器中使用旧浏览器中的普通功能,并且还要检查polyfill option of map method。
var myArray = [{
name: 'cheesesteak'
}, {
name: 'hamburger'
}, {
name: 'pork roll'
}];
var jawn = myArray.map(function(v) {
return v.name
}).join();
console.log(jawn);

答案 1 :(得分:3)
var myArray = [{
name: 'cheesesteak'
}, {
name: 'hamburger'
}, {
name: 'pork roll'
}];
var jawn = myArray.map(function(it) {
return it.name;
}).join();
console.log(jawn);
答案 2 :(得分:2)
lodash(v4):
var result = _.map(myArray ,'name').join(',');
<强> underscorejs 强>
var result = _.pluck(myArray ,'name').join(',');