对对象数组中的值执行.join [英] Perform .join on value in array of objects

查看:284
本文介绍了对对象数组中的值执行.join的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个字符串数组,我可以使用 .join()方法获取单个字符串,每个元素用逗号分隔,如下所示: / p>

If I have an array of strings, I can use the .join() method to get a single string, with each element separated by commas, like so:

["Joe", "Kevin", "Peter"].join(", ") // => "Joe, Kevin, Peter"

我有一个对象数组,我想表演对其中所持有的价值进行类似的操作;所以来自

I have an array of objects, and I’d like to perform a similar operation on a value held within it; so from

[
  {name: "Joe", age: 22},
  {name: "Kevin", age: 24},
  {name: "Peter", age: 21}
]

仅在 name 属性上执行 join 方法,以实现与之前。

perform the join method only on the name attribute, to achieve the same output as before.

目前我有以下功能:

function joinObj(a, attr){
  var out = [];

  for (var i = 0; i < a.length; i++){
    out.push(a[i][attr]);
  }

  return out.join(", ");
}

该代码没有任何问题,它有效,但突然间我已经从一个简单,简洁的代码行转变为一个非常重要的功能。是否有更简洁,更理想的写作方式?

There’s nothing wrong with that code, it works, but all of a sudden I’ve gone from a simple, succinct line of code to a very imperative function. Is there a more succinct, ideally more functional way of writing this?

推荐答案

如果你想将对象映射到某个东西(在此案件属性)。我认为 Array.prototype.map 如果您想要在功能上进行编码,那么就是您要找的。

If you want to map objects to something (in this case a property). I think Array.prototype.map is what you're looking for if you want to code functionally.

[
  {name: "Joe", age: 22},
  {name: "Kevin", age: 24},
  {name: "Peter", age: 21}
].map(function(elem){
    return elem.name;
}).join(",");

在现代JavaScript中:

In modern JavaScript:

[
  {name: "Joe", age: 22},
  {name: "Kevin", age: 24},
  {name: "Peter", age: 21}
].map(e => e.name).join(",");

(小提琴)

如果你想支持旧浏览器,那不是 ES5投诉你可以填充它(上面的MDN页面上有一个polyfill)。另一种方法是使用underscorejs的 pluck 方法:

If you want to support older browsers, that are not ES5 complaint you can shim it (there is a polyfill on the MDN page above). Another alternative would be to use underscorejs's pluck method:

var users = [
      {name: "Joe", age: 22},
      {name: "Kevin", age: 24},
      {name: "Peter", age: 21}
    ];
var result = _.pluck(users,'name').join(",")

这篇关于对对象数组中的值执行.join的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆