Search code examples
javascripttypescriptangular7angular-directiveangular-components

How to return values separated by comma from array?


I work on angular 7 I face Issue: I can't separate returned values of ZCO by comma from OriginCountry.

Origin Country is an array of an object I need to collect property ZCO from it

separated by a comma when it has multiple values so How to do that?

on component.ts

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

data returned from OriginCountry as below :

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

ON Component.html

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

Expected Result to be :

Japan,China

Solution

  • Other solution, this relies on 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);