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

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

问题描述

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

["Joe", "Kevin", "Peter"].join(", ")//=>乔、凯文、彼得"

我有一个对象数组,我想对其中保存的值执行类似的操作;所以从

<预><代码>[{姓名:乔",年龄:22},{姓名:凯文",年龄:24},{姓名:彼得",年龄:21}]

仅对 name 属性执行 join 方法,以实现与以前相同的输出.

目前我有以下功能:

function joinObj(a, attr){var out = [];for (var i = 0; i < a.length; i++){out.push(a[i][attr]);}return out.join(", ");}

那段代码没有任何问题,它可以工作,但突然间我从一行简单、简洁的代码变成了一个非常命令式的函数.有没有更简洁、理想情况下更实用的写法?

解决方案

如果您想将对象映射到某物(在本例中为属性).我认为 Array.prototype.map 如果您想按功能进行编码,这就是您要寻找的.

console.log([{姓名:乔",年龄:22},{姓名:凯文",年龄:24},{姓名:彼得",年龄:21}].map(函数(元素){返回 elem.name;}).join(","));

在现代 JavaScript 中:

console.log([{姓名:乔",年龄:22},{姓名:凯文",年龄:24},{姓名:彼得",年龄:21}].map(e => e.name).join(","));

(小提琴)

如果您想支持不符合ES5的旧版浏览器,您可以填充它(上面的 MDN 页面上有一个 polyfill).另一种选择是使用 underscorejs 的 pluck 方法:

var users = [{姓名:乔",年龄:22},{姓名:凯文",年龄:24},{姓名:彼得",年龄:21}];var 结果 = _.pluck(users,'name').join(",")

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.

Currently I have the following function:

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?

解决方案

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.

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

In modern JavaScript:

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

(fiddle)

If you want to support older browsers, that are not ES5 compliant 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天全站免登陆