如何从数组中返回以逗号分隔的值?

Posted

技术标签:

【中文标题】如何从数组中返回以逗号分隔的值?【英文标题】:How to return values separated by comma from array? 【发布时间】:2020-10-27 08:47:25 【问题描述】:

我在 Angular 7 上工作,我面临问题:我无法用 OriginCountry 的逗号分隔 ZCO 的返回值。

Origin Country 是一个对象数组,我需要从中收集属性 ZCO

当它有多个值时用逗号分隔那么怎么做?

关于组件.ts

OriginCountry:any[]=[];  
this.OriginCountry = this.partDetailsService.currentData.OriginCountry;  
console.log("country origion" + JSON.stringify(this.OriginCountry) )

OriginCountry 返回的数据如下:

[
   CO: "zx", ZCO: "China", InfSrc: "FMD", TP: "Factory" ,
   CO: "zy", ZCO: "Japan", InfSrc: "FMD", TP: "Factory" 
];

打开组件.html

<div *ngFor="let country of OriginCountry">
  country.ZCO
</div>

预期结果是:

Japan,China

【问题讨论】:

【参考方案1】:

你甚至不需要ngFor

const csv = [
             "CO":"zx","ZCO":"China","InfSrc":"FMD","TP":"Factory", 
             "CO":"zy","ZCO":"Japan","InfSrc":"FMD","TP":"Factory"
            ]
            .map((ZCO) => ZCO).join();

然后:

<div>
  csv
</div>

【讨论】:

【参考方案2】:

其他解决方案,这个依赖reduce

const csv = [
             "CO":"zx","ZCO":"China","InfSrc":"FMD","TP":"Factory", 
             "CO":"zy","ZCO":"Japan","InfSrc":"FMD","TP":"Factory"
            ]
            .reduce((ZCOs, co) => [...ZCOs, co.ZCO], []).join(', ');
            
console.log(csv);

【讨论】:

以上是关于如何从数组中返回以逗号分隔的值?的主要内容,如果未能解决你的问题,请参考以下文章

如何在Javascript中用逗号分隔的值匹配数组?

如何分离从表行中获取的值并将其存储在雪花中的数组中

sql 如何以逗号为分隔符分割一个字段的值

python 如何以逗号为分隔符输出数组

如何使用 in() 函数从 mysql 存储函数返回的值?

php 如何从mysql输出数组用逗号分隔?