Javascript对象数组中的值会被执行。加入 [英] Javascript perform .join on value in object array

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

问题描述

如果我有一个字符串数组,我可以使用。加入()的方法来得到一个字符串,用逗号分隔每个元素 - 像这样:

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}
]

仅在名称属性执行加入方法,因为之前达到同样的输出。

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(", ");
}

有什么不妥code,它的工作原理是,但突然间我从code的简单,简洁的线条去了一个非常必要的功能。有没有写这个的更简洁,更理想的功能的方式?

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?

推荐答案

如果要映射对象的东西(在这种情况下属性)。我认为,<一个href=\"https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/map\"><$c$c>Array.prototype.map是你在找什么,如果你想code功能。

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(",");

(小提琴)

如果你想支持旧的浏览器,不属于 ES5投诉可以垫片(其中有在MDN页面上的填充工具上文)。另一种方法是使用underscorejs的 勇气 方式:

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(",")

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

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