Javascript将数组中对象的属性转换为字符串 [英] Javascript turn property of objects in array into a string

查看:103
本文介绍了Javascript将数组中对象的属性转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象数组,它们都是同一类的所有实例,如下所示:

I have an array of objects which are all instances of the same class like below:

class Foo {
    constructor(bar){
        this.bar = bar;
    }
}

var myArr = [new Foo("1"), new Foo("2"), new Foo("3"), new Foo("4")];

我希望能够将数组中每个对象的bar属性加入逗号分隔的字符串中。

I want to be able to join the bar property of each object in the array into a comma separated string.

是否可以在对象的属性上调用.join方法?如果不是低于最有效的方法呢?

Is it possible to call the .join method on the property of an object? If not is below the most efficent way to do this?

 var result = "";
 for (var i = 0; i < myArr.length; i++){
     result += myArr[i].bar+","
 }

还是还有其他方法?

推荐答案

您可以使用 Array.prototype.map

You can use Array.prototype.map:

var result = myArr.map(function(x) { return x.bar; }).join(',');

这篇关于Javascript将数组中对象的属性转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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